1 回答

TA貢獻2036條經驗 獲得超8個贊
輸入:
In [77]: X
Out[77]:
array([[inf, 1., inf],
[inf, 2., 4.],
[ 3., 4., 5.]])
In [78]: M
Out[78]:
array([[1, 0, 0],
[0, 1, 0],
[0, 1, 0]])
方法
首先,我們需要反轉掩碼M,然后使用numpy.where; 有了這些索引,我們就可以將原始數組中的元素設置為零,方法如下:
# inverting the mask
In [59]: M_not = np.logical_not(M)
In [80]: M_not
Out[80]:
array([[False, True, True],
[ True, False, True],
[ True, False, True]])
# get the indices where `True` exists in array `M_not`
In [81]: indices = np.where(M_not)
In [82]: indices
Out[82]: (array([0, 0, 1, 1, 2, 2]), array([1, 2, 0, 2, 0, 2]))
# zero out the elements
In [84]: X[indices] = 0
In [61]: X
Out[61]:
array([[inf, 0., 0.],
[0., 2., 0.],
[0., 4., 0.]])
PS反轉掩碼不應理解為矩陣反轉。應該理解為翻轉布爾值(True--> False; False--> True)
添加回答
舉報