替换掩码 numpy 数组中的值不起作用

Replace values in masked numpy array not working

我知道了。 numpy 中的屏蔽数组称为 arr,形状为 (50, 360, 720):

masked_array(data =
 [[-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]
 ..., 
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]
 [-- -- -- ..., -- -- --]],
             mask =
 [[ True  True  True ...,  True  True  True]
 [ True  True  True ...,  True  True  True]
 [ True  True  True ...,  True  True  True]
 ..., 
 [ True  True  True ...,  True  True  True]
 [ True  True  True ...,  True  True  True]
 [ True  True  True ...,  True  True  True]],
       fill_value = 1e+20)

它有作用。 arr[0] 中的数据:

arr[0].data

array([[-999., -999., -999., ..., -999., -999., -999.],
       [-999., -999., -999., ..., -999., -999., -999.],
       [-999., -999., -999., ..., -999., -999., -999.],
       ..., 
       [-999., -999., -999., ..., -999., -999., -999.],
       [-999., -999., -999., ..., -999., -999., -999.],
       [-999., -999., -999., ..., -999., -999., -999.]])

-999。是 missing_value,我想用 0.0 替换它。我这样做:

arr[arr == -999.] = 0.0

然而,即使在这个操作之后,arr 仍然保持不变。如何解决这个问题?

也许你想要 filled。我来举例说明:

In [702]: x=np.arange(10)    
In [703]: xm=np.ma.masked_greater(x,5)

In [704]: xm
Out[704]: 
masked_array(data = [0 1 2 3 4 5 -- -- -- --],
             mask = [False False False False False False  True  True  True  True],
       fill_value = 999999)

In [705]: xm.filled(10)
Out[705]: array([ 0,  1,  2,  3,  4,  5, 10, 10, 10, 10])

在这种情况下,filled 将所有掩码值替换为填充值。如果没有参数,它将使用 fill_value.

np.ma 使用这种方法来执行其许多计算。例如,它的 sum 就好像我用 0 填充了所有屏蔽值一样。prod 会将它们替换为 1。

In [707]: xm.sum()
Out[707]: 15
In [709]: xm.filled(0).sum()
Out[709]: 15

filled 的结果是一个常规数组,因为所有掩码值都已替换为 'normal'。