Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 817
excavator Avatar asked Feb 17 '16 19:02

excavator


People also ask

How do you make a 1D array into a 2D array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.


1 Answers

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]])
like image 188
Padraic Cunningham Avatar answered Oct 07 '22 17:10

Padraic Cunningham