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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3