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]]
我有一个numpy 2D数组[[1,2,3]]。我需要给它添加一个numpy 1D数组(比如[4,5,6]),这样它就会变成[[1,2,3],[4,5,6]]
This is easily possible using lists, where you just call append on the 2D list.
使用列表很容易做到这一点,您只需调用2D列表上的append。
But how do you do it in Numpy arrays?
但是如何在Numpy数组中实现呢?
np.concatenate
and np.append
dont work. they convert the array to 1D for some reason.
np。连接和np。附加不工作。由于某种原因,它们将数组转换为1D。
Thanks!
谢谢!
1 个解决方案
#1
9
You want vstack:
你想要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]])
#1
9
You want vstack:
你想要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]])