2014-07-24 86 views
2

我有兩個2D numpy的數組:numpy的二維數組操作,保持一定的位置

X2d = np.array([[0,4,5,0], 
       [7,8,4,3], 
       [0,0,9,8]]) 

Y2d = np.array([[1,0,4,8], 
       [0,3,8,5], 
       [0,6,0,8]]) 

#and I would like to get these two: 

X2dresult = np.array([[0,0,5,0], 
         [0,8,4,3], 
         [0,0,0,8]]) 

Y2dresult = np.array([[0,0,4,0], 
         [0,3,8,5], 
         [0,0,0,8]]) 

所以基本上我需要讓那些兩個矩陣是大於0我可以使用numpy.where功能位置或類似的東西來獲得這些結果? 感謝

回答

2

您可以使用按位AND或OR和numpy.where這個:

>>> X2d = np.array([[0,4,5,0], 
...     [7,8,4,3], 
...     [0,0,9,8]]) 
>>> 
>>> Y2d = np.array([[1,0,4,8], 
...     [0,3,8,5], 
...     [0,6,0,8]]) 
>>> indices = np.where(~((X2d > 0) & (Y2d > 0))) 
>>> X2d[indices] = 0 
>>> Y2d[indices] = 0 
>>> X2d 
array([[0, 0, 5, 0], 
     [0, 8, 4, 3], 
     [0, 0, 0, 8]]) 
>>> Y2d 
array([[0, 0, 4, 0], 
     [0, 3, 8, 5], 
     [0, 0, 0, 8]]) 

我覺得按位OR是更好,更清晰的閱讀:

>>> X2d = np.array([[0,4,5,0], 
...     [7,8,4,3], 
...     [0,0,9,8]]) 
>>> 
>>> Y2d = np.array([[1,0,4,8], 
...     [0,3,8,5], 
...     [0,6,0,8]]) 
>>> indices = np.where((X2d == 0) | (Y2d == 0)) 
>>> X2d[indices] = 0 
>>> Y2d[indices] = 0 
>>> X2d 
array([[0, 0, 5, 0], 
     [0, 8, 4, 3], 
     [0, 0, 0, 8]]) 
>>> Y2d 
array([[0, 0, 4, 0], 
     [0, 3, 8, 5], 
     [0, 0, 0, 8]]) 
0
X2dresult = ((X2d > 0) & (Y2d > 0)) * X2d 
Y2dresult = ((X2d > 0) & (Y2d > 0)) * Y2d 

Z = ((X2d > 0) & (Y2d > 0)),然後Z[i,j] = True當且僅當X2d[i,j] > 0Y2d[i,j] > 0

現在X2dresult = Z * X2d,所以X2dresult[i,j] = Z[i,j] * X2d[i,j],這是0,如果Z[i,j] = FalseX2d[i,j]如果Z[i,j] = True。 (因爲int(True) = 1int(False) = 0

所以,在X2dresult數組所有元素都是在那些位置處或者X2dY2d具有00

+0

請向您的代碼添加一些解釋。目前,它被自動標記爲低質量帖子。 –