在numpy中连接两个多维数组

had*_*i k 2 python numpy concatenation

我有两个数组AB

>> np.shape(A)
>> (7, 6, 2)
>> np.shape(B)
>> (6,2)
Run Code Online (Sandbox Code Playgroud)

现在,我要连接的两个阵列,从而A扩展到(8,6,2)A[8] = B

我试过 np.concatenate()

>> np.concatenate((A,B),axis = 0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-d614e94cfc50> in <module>()
----> 1 np.concatenate((A,B),axis = 0)

ValueError: all the input arrays must have same number of dimensions  
Run Code Online (Sandbox Code Playgroud)

np.vstack()

>> np.vstack((A,B))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-41-7c091695f277> in <module>()
----> 1 np.vstack((A,B))
//anaconda/lib/python2.7/site-packages/numpy/core/shape_base.pyc in vstack(tup)
    228 
    229     """
--> 230     return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
    231 
    232 def hstack(tup):

ValueError: all the input arrays must have same number of dimensions
Run Code Online (Sandbox Code Playgroud)

arm*_*ita 5

可能最简单的方法是像这样使用 numpy newaxis

import numpy as np

A = np.zeros((7, 6, 2))
B = np.zeros((6,2))
C = np.concatenate((A,B[np.newaxis,:,:]),axis=0)
print(A.shape,B.shape,C.shape)
Run Code Online (Sandbox Code Playgroud)

,这导致:

(7, 6, 2) (6, 2) (8, 6, 2)
Run Code Online (Sandbox Code Playgroud)

正如@sascha 提到的,您可以使用vstack(另请参阅hstackdstack)通过隐式轴(分别为axis = 0axis = 1axis =2)执行直接连接操作:

D = np.vstack((A,B[np.newaxis,:,:]))
print(D.shape)
Run Code Online (Sandbox Code Playgroud)

, 结果:

(8, 6, 2)
Run Code Online (Sandbox Code Playgroud)