excavator
excavator

Reputation: 403

Append a 1d array to a 2d array in Numpy Python

I have a numpy 2D array [[1,2,3]]. I need to append a numpy 1D array,( say [4,5,6]) to it, so that it becomes [[1,2,3], [4,5,6]]

This is easily possible using lists, where you just call append on the 2D list.

But how do you do it in Numpy arrays?

np.concatenate and np.append dont work. they convert the array to 1D for some reason.

Thanks!

Upvotes: 21

Views: 70263

Answers (2)

Wattanapong Suttapak
Wattanapong Suttapak

Reputation: 111

Try this:

np.concatenate(([a],[b]),axis=0)

when

a = np.array([1,2,3])
b = np.array([4,5,6])

then result should be:

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

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You want vstack:

In [45]: a = np.array([[1,2,3]])

In [46]: l = [4,5,6]

In [47]: np.vstack([a,l])
Out[47]: 
array([[1, 2, 3],
       [4, 5, 6]])

You can stack multiple rows on the condition that The arrays must have the same shape along all but the first axis.

In [53]: np.vstack([a,[[4,5,6], [7,8,9]]])
Out[53]: 
array([[1, 2, 3],
       [4, 5, 6],
       [4, 5, 6],
       [7, 8, 9]])

Upvotes: 18

Related Questions