如何使用布尔数组将np.infs清零数组的所有索引?

问题描述 投票:1回答:1

我有一个带有inf值的矩阵和一个布尔数组,用于指示要保留的值。如何使用布尔数组将原始矩阵中的所有值清零,包括infs,但保留所有infs对应于Trues?

X     = [inf, 1, inf]
        [inf, 2,   4]
        [3,   4,   5]

M     = [1,   0,   0]
        [0,   1,   0]
        [0,   1,   0]

(current output)
M * X = [inf, 0, nan]
        [nan, 2,   0]
        [0,   4,   0]

(desired output)
M * X = [inf, 0,   0]
        [0,   2,   0]
        [0,   4,   0]
python numpy boolean linear-algebra infinity
1个回答
1
投票

输入:

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.]])

附:反转掩模不应被理解为矩阵反转。应该理解为翻转布尔值(True - > False; False - > True

© www.soinside.com 2019 - 2024. All rights reserved.