2016-08-25 105 views
1

我與陣列數據替換時有一個問題: 說,numpy ---如何用數組中的某些多元素同時替換?

a = [1, 0, 0] 
b = [0, 0, 0] 
c = [0, 0] 
X = numpy.zeros((3, 3, 2)) 

和我有矩陣Y具有形狀(2,3,2)和它是非零矩陣

現在;我想直接用Y等於X的這些元素;

X[tuple(numpy.where(a==0)[0]), 
    tuple(numpy.where(b==0)[0]), 
    tuple(numpy.where(c==0)[0])] = Y 

我得到了錯誤shape mismatch: objects cannot be broadcast to a single shape

+0

不'索引Y'具有形狀(3,3,2),而不是(2,3,2)? – unutbu

+0

否,Y = [[[0 48] [27 27] [44 44]] [[0. 0.] [44 44] [0.43。 ]]] –

+0

Y的大小是(2,3,2)。我想在X中替換它,但是在某些地方 –

回答

1

你可以使用np.ix_構建適當的索引數組索引X

import numpy as np 
np.random.seed(2016) 
a=np.array([1, 0, 0]) 
b=np.array([0, 0, 0]) 
c=np.array([0, 0]) 
X = np.zeros((3,3,2)) 
Y = np.random.randint(1, 10, size=(2,3,2)) 

idx = np.ix_(a==0, b==0, c==0) 
X[idx] = Y 
print(X) 

產量

array([[[ 0., 0.], 
     [ 0., 0.], 
     [ 0., 0.]], 

     [[ 9., 8.], 
     [ 3., 7.], 
     [ 4., 5.]], 

     [[ 2., 2.], 
     [ 3., 3.], 
     [ 9., 9.]]]) 

或者,可以構造一個布爾掩碼

mask = (a==0)[:,None,None] & (b==0)[None,:,None] & (c==0)[None,None,:] 
X[mask] = Y 

索引(a=0)(a==0)[:,None,None]adds new axes到1D布爾數組(a=0)(a==0)[:,None,None]有形狀(3,1,1)。類似地,(b==0)[None,:,None]具有形狀(1,3,1),並且(c==0)[None,None,:]具有形狀(1,1,2)。

當與&(按位與)組合時,三個陣列是broadcasted到一個共同的形狀,(3,3,2)。因此,X得到由形狀(3,3,2)中的一個布爾值陣列中

X[mask] = Y 
+0

非常感謝,但是,如果Y的尺寸是(2,3,2),有什麼辦法可以做。我說的是,如果Y的大小不同,我可以做些什麼來將它存儲到X中? –

+0

再次感謝一百萬次,它效果很好......我說X [mask] = Y ....它很好用 –

相關問題