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

How to Add an Extra Column to a NumPy Array?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 00:13:02849browse

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>

For example, given the following 2D array:

<code class="python">a = np.array([
    [1, 2, 3],
    [2, 3, 4],
])</code>

To add a column of zeros, we can use:

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

This will result in the following array:

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

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!

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