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!
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With