Python 在numpy中将二维数组追加到一维数组

Python 在numpy中将二维数组追加到一维数组,python,numpy,Python,Numpy,我有一个空的numpy数组,现在我想附加一个2d数组 >>> import numpy as np >>> a = np.array([]) >>> b = np.array([[1, 2], [3, 4]]) >>> np.append(a, b) array([1, 2, 3, 4]) 但是我想要[[1,2],[3,4]]这里有两种方法可以将“空”数组与2d数组连接起来,生成一个与原始数组相似的新数组: In [123

我有一个空的numpy数组,现在我想附加一个2d数组

>>> import numpy as np
>>> a = np.array([])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.append(a, b)
array([1, 2, 3, 4])

但是我想要
[[1,2],[3,4]]

这里有两种方法可以将“空”数组与2d数组连接起来,生成一个与原始数组相似的新数组:

In [123]: b = np.array([[1, 2], [3, 4]])
In [124]: b.shape
Out[124]: (2, 2)
In [125]: np.concatenate((np.zeros((2,0),int),b),axis=1)
Out[125]: 
array([[1, 2],
       [3, 4]])
In [126]: _.shape
Out[126]: (2, 2)

In [127]: np.concatenate((np.zeros((0,2),int),b),axis=0)
Out[127]: 
array([[1, 2],
       [3, 4]])
通常关于尺寸数匹配和非连接形状匹配的规则适用。还要注意
dtype

append
vstack
hstack
摆弄形状,然后进行
连接
。最好了解如何直接使用
串联

但有人可能会问,为什么要进行所有这些串联工作,只为了生成一个匹配的数组<代码>b.复制()更简单

如果这是循环的开始,不要。使用list append构建数组列表,然后在末尾连接一次
concatenate
获取数组列表
np.append
只接受2个输入,并以不同的方式处理它们。我不鼓励使用它

编辑 你真的想要3d效果而不是2d效果吗

In [128]: np.array([[[1, 2], [3, 4]]])
Out[128]: 
array([[[1, 2],
        [3, 4]]])
In [129]: _.shape
Out[129]: (1, 2, 2)
我写的关于使用匹配维度连接的
的内容仍然适用。例如,创建一个具有正确形状的“空”,即
(0,2,2)
,并将
b
展开到
(1,2,2)

b[None,…]
是(1,2,2),因此不需要连接任何内容


有一个
np.stack
,它向所有输入数组添加一个维度,然后连接起来。但我不认为这在这里适用。唯一可以通过堆栈添加到(2,2)数组的是另一个(2,2)数组。

以下是使其工作的一种方法:

# start with zero layers of the right shape:
>>> a = np.empty((0, 2, 2), int)
>>> a
array([], shape=(0, 2, 2), dtype=int64)
>>> b = np.arange(1, 5).reshape(2, 2)
>>> b
array([[1, 2],
       [3, 4]])
# use np.r_ instead of append the spec string '0,3,1' means concatenate
# along axis 0, make everything 3D, operands with fewer than 3
# get 1 axis added on the left
>>> np.r_['0,3,1', a, b]
array([[[1, 2],
        [3, 4]]])

a=b
开始,然后调用
np。在循环
np中追加(a,b,axis=0)
。追加有两种模式。如果没有轴
,您会发现,它会使一切变得平坦。使用
时,它只执行
串联
,需要匹配的维度。似乎很多海报都没有注意到这样的函数文档。
# start with zero layers of the right shape:
>>> a = np.empty((0, 2, 2), int)
>>> a
array([], shape=(0, 2, 2), dtype=int64)
>>> b = np.arange(1, 5).reshape(2, 2)
>>> b
array([[1, 2],
       [3, 4]])
# use np.r_ instead of append the spec string '0,3,1' means concatenate
# along axis 0, make everything 3D, operands with fewer than 3
# get 1 axis added on the left
>>> np.r_['0,3,1', a, b]
array([[[1, 2],
        [3, 4]]])