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

How to Add a Column to a NumPy Array?

DDD
Release: 2024-11-06 15:22:02
Original
995 people have browsed it

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

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

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

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

To add multiple columns:

<code class="python">d = np.c_[a, 2*np.ones(a.shape[0]), 3*np.ones(a.shape[0])]</code>
Copy after login

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!

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