简体   繁体   中英

Appending arrays with NumPy

Using NumPy, I want to create an n-by-2 array, by starting with an empty array, and adding on some 1-by-2 arrays.

Here's what I have tried so far:

x = np.array([1, 2])
y = np.array([3, 4])
z = np.array([])
z = np.append(z, x)
z = np.append(z, y)

However, this gives me:

z = [1, 2, 3, 4]

What I want is:

z = [[1, 2], [3, 4]]

How can I achieve this?

import numpy as np

x = np.array([1, 2])
y = np.array([3, 4])
z = np.append([x],[y], axis=0)

print(z)

>>> [[1 2]
     [3 4]]

No need to create the array before appending, axis=0 will allow you to append row wise.

The previous works if z is not an array already. From then on you specify z as the original array and append the other array as such:

t = np.array([5, 6])
z = np.append(z,[t], axis=0)
print(z)

[[1 2]
 [3 4]
 [5 6]]

You can simply use np.array :

>>> np.array((x,y))
array([[1, 2],
       [3, 4]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM