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

How to Add Extra Columns to a NumPy Array?

DDD
Release: 2024-11-04 20:43:02
Original
328 people have browsed it

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],
])
Copy after login

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])]
Copy after login

This will create a new array b with an additional column of zeros:

b = np.array([
    [1, 2, 3, 0],
    [2, 3, 4, 0],
])
Copy after login

Alternatively, you can use the np.r_[ ] function:

b = np.r_[a, np.zeros((a.shape[0], 1))]
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template