Home > OS >  Add elements to 2-D array
Add elements to 2-D array

Time:05-03

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?

CodePudding user response:

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.

CodePudding user response:

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]])
  • Related