简体   繁体   中英

Add elements to 2-D array

I have the following Arrays

import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([5,6])

Now I want to add the second element of A to B using the append function:

B = np.append(B, A[1])

What I want to get is:

B = np.array([[5, 6],[3,4]])

But what I get is:

B = np.array([5, 6, 3, 4])

How can I solve this? Should I use another function instead of numpy.append?

import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([[5,6]])
B = np.append(B, [A[1]], axis=0)
print(B)

Output

array([[5, 6],
       [3, 4]])

This would be one of the way using np.append() specifying the axis = 0 .

You can use np.stack for this instead of np.append :

>>> np.stack([B, A[1]])
array([[5, 6],
       [3, 4]])

You could also add [:, None] to your two arrays and append with axis=1 :

>>> np.append(B[:, None], A[1][:, None], axis=1)
array([[5, 3],
       [6, 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