How to Add an Extra Column to a NumPy Array?

Linda Hamilton
Release: 2024-11-06 00:13:02
Original
768 people have browsed it

How to Add an Extra Column to a NumPy Array?

Appending an Additional Column to a NumPy Array

Adding an extra column to a NumPy array is a straightforward task that can be accomplished using the np.c_ function. This function is specifically designed for concatenating arrays along columns, making it an ideal choice for this purpose.

To append a column of zeros, simply use the following syntax:

<code class="python">np.c_[array, np.zeros((array.shape[0], 1))]</code>
Copy after login

For example, given 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, we can use:

<code class="python">b = np.c_[a, np.zeros((a.shape[0], 1))]</code>
Copy after login

This will result in the following array:

<code class="python">b = np.array([
    [1, 2, 3, 0],
    [2, 3, 4, 0],
])</code>
Copy after login

Note:

  • The np.zeros() function creates a new array of zeros with the specified shape.
  • The np.c_ function requires square brackets ([ ]) instead of parentheses (( )), as it uses these brackets to concatenate arrays along columns.
  • This method can also be used to append multiple additional columns at once, by passing a tuple or list of arrays.
  • The np.r_ function (similar to np.c_) can be used to concatenate arrays horizontally, though square brackets should be used for this function as well.

The above is the detailed content of How to Add an Extra 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!