2016-05-12 25 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)