你可以使用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
不'索引Y'具有形狀(3,3,2),而不是(2,3,2)? – unutbu
否,Y = [[[0 48] [27 27] [44 44]] [[0. 0.] [44 44] [0.43。 ]]] –
Y的大小是(2,3,2)。我想在X中替換它,但是在某些地方 –