Home > Article > Backend Development > How to Add a Column to a NumPy Array?
How to Augment NumPy Arrays with an Additional Column
When working with NumPy arrays, it is often necessary to add an extra column to an existing array. This can be achieved using various methods, one of which is by employing NumPy's np.c_[...] function.
Consider the following 2D array:
<code class="python">a = np.array([ [1, 2, 3], [2, 3, 4], ])</code>
To add a column of zeros to this array, we can use np.c_[...]:
<code class="python">b = np.c_[a, np.zeros(a.shape[0])]</code>
This will create a new array b with an additional column of zeros, resulting in:
<code class="python">b = np.array([ [1, 2, 3, 0], [2, 3, 4, 0], ])</code>
Another alternative for adding columns is to use the np.r_[...] function. It can be utilized to append rows and columns to arrays, offering greater flexibility.
For instance, to add an additional column of ones:
<code class="python">c = np.c_[a, np.ones(a.shape[0])]</code>
To add multiple columns:
<code class="python">d = np.c_[a, 2*np.ones(a.shape[0]), 3*np.ones(a.shape[0])]</code>
The square bracket notation [...] in these functions allows for flexible column additions by specifying values or arrays in the desired locations.
The above is the detailed content of How to Add a Column to a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!