2016-05-12 23 views
1

我有两个数组AB连接两个在numpy的多维数组

>> np.shape(A) 
>> (7, 6, 2) 
>> np.shape(B) 
>> (6,2) 

现在,我想与A[8] = B

我试图np.concatenate()

来连接两个数组,使得 A扩展到 (8,6,2)
>> 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 

and 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 
+3

DO [此](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy。首先在concat之前扩展.dims.html)。 – sascha

+0

嘿谢谢,它工作:)首先使用'expand_dims'然后'np.concatanate'。顺便说一句,你是什么意思,用更具表现力的'np.vstack'然后concat? –

+0

我没有看到你也尝试过np.vstack。在这种情况下,我宁愿vstack,因为它不需要参数,并且可以立即看到发生了什么。如果你需要做很多的expand_dims,你也可以尝试文档中提到的newaxis-approach(你只需要添加索引到B)。它有点短。 – sascha

回答

2

可能是最简单的方法是使用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) 

,从而导致此:

(7, 6, 2) (6, 2) (8, 6, 2) 

正如@sascha提到你可以使用vstack(见hstack,dstack)与隐式轴执行直接级联操作(分别为axis = 0,axis = 1axis =2):

D = np.vstack((A,B[np.newaxis,:,:])) 
print(D.shape) 

,结果:

(8, 6, 2)