Home  >  Article  >  Backend Development  >  How to Add Extra Columns to a NumPy Array?

How to Add Extra Columns to a NumPy Array?

DDD
DDDOriginal
2024-11-04 20:43:02264browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn