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

2024-06-02 08:52:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有inf值的矩阵和一个指示要保留哪些值的布尔数组。如何使用布尔数组将原始矩阵(包括inf)中的所有值归零,但使所有inf都对应于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]

Tags: output矩阵数组currentnaninfdesiredtrues
1条回答
网友
1楼 · 发布于 2024-06-02 08:52:12

输入

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

p.S.反转掩模不应理解为矩阵反转。应该理解为翻转布尔值(True>FalseFalse>True

相关问题 更多 >