简体   繁体   English

将一维数组附加到 Numpy Python 中的二维数组

[英]Append a 1d array to a 2d array in Numpy Python

I have a numpy 2D array [[1,2,3]] .我有一个 numpy 二维数组[[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 一维数组,(比如[4,5,6] ),使它变成[[1,2,3], [4,5,6]]

This is easily possible using lists, where you just call append on the 2D list.使用列表很容易做到这一点,您只需在二维列表上调用append 即可

But how do you do it in Numpy arrays?但是你如何在 Numpy 数组中做到这一点呢?

np.concatenate and np.append dont work. np.concatenatenp.append不起作用。 they convert the array to 1D for some reason.他们出于某种原因将数组转换为一维。

Thanks!谢谢!

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

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]])数组([[1, 2, 3], [4, 5, 6]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM