Home > Article > Backend Development > How to Add Extra Columns to a NumPy Array?
Adding Extra Columns to a NumPy Array
Suppose you have a 2D NumPy array a as follows:
a = np.array([ [1, 2, 3], [2, 3, 4], ])
To add a column of zeros along the second axis, you can utilize various methods. One approach is to employ the np.c_[ ] function:
b = np.c_[a, np.zeros(a.shape[0])]
This will create a new array b with an additional column of zeros:
b = np.array([ [1, 2, 3, 0], [2, 3, 4, 0], ])
Alternatively, you can use the np.r_[ ] function:
b = np.r_[a, np.zeros((a.shape[0], 1))]
This method will also add a column of zeros to the array.
Note that np.r_[ ] and np.c_[ ] provide flexible options for modifying array dimensions. They can be utilized to mix vectors and scalars, add rows or columns, and even insert entire arrays at specified positions.
The above is the detailed content of How to Add Extra Columns to a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!