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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35466455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:28:41  来源:igfitidea点击:

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

pythonarraysnumpyappend

提问by excavator

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 二维数组[[1,2,3]]。我需要在它上面附加一个 numpy 1D 数组,(比如说[4,5,6]),这样它就变成了[[1,2,3], [4,5,6]]

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

使用列表很容易做到这一点,您只需在二维列表上调用append 即可

But how do you do it in Numpy arrays?

但是你如何在 Numpy 数组中做到这一点呢?

np.concatenateand np.appenddont work. they convert the array to 1D for some reason.

np.concatenate并且np.append不工作。他们出于某种原因将数组转换为一维。

Thanks!

谢谢!

采纳答案by Padraic Cunningham

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

回答by Wattanapong Suttapak

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