Home >Backend Development >Python Tutorial >How can I append an extra column to a NumPy array?

How can I append an extra column to a NumPy array?

DDD
DDDOriginal
2024-11-06 14:04:02311browse

How can I append an extra column to a NumPy array?

Appending an Extra Column to a NumPy Array

NumPy, Python's versatile scientific computing library, empowers users to effortlessly manipulate and analyze multidimensional arrays. One common operation is adding an additional column to an existing array. To achieve this, you can utilize several methods, including:

np.c_[...] and np.r_[...]

As alternatives to np.hstack and np.vstack, np.c_[...] and np.r_[...] offer flexible options for column and row addition, respectively. They employ square brackets [] instead of parentheses ().

Consider an example:

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

# Add a column of zeros to the right
b = np.c_[a, np.zeros(a.shape[0])]

print(b)
# [[1 2 3 0]
#  [2 3 4 0]]</code>

Key Differences

The primary distinction between np.c_[...] and np.r_[...] lies in their operation. np.c_[...] appends columns, allowing you to concatenate multiple arrays along the second axis. In contrast, np.r_[...] appends rows, enabling the concatenation of arrays along the first axis.

Usage Examples

Here are additional examples to illustrate the versatility of np.c_[...] and np.r_[...]:

<code class="python"># Adding a column of ones to the left of array A
A = np.eye(3)
b = np.c_[np.ones(A.shape[0]), A]

# Adding a row below array A
c = np.r_[A, [A[1]]]

# Mixing vectors and scalars
d = np.r_[A[0], [1, 2, 3], A[1]]</code>

Conclusion

By leveraging np.c_[...] and np.r_[...], you can seamlessly add columns and rows to your NumPy arrays, empowering you to manipulate data effectively and efficiently.

The above is the detailed content of How can I append 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