Skip to main content
 首页 » 编程设计

python之numpy masked_array 掩码更改类型

2024年10月01日6bluestorm

如果值不在数组中,np.ma.masked_equal 或 masked_values 不会创建 False 掩码,我对此感到有点惊讶,但是而不是标量。

示例:

y = np.arange(10) 
yy = np.ma.masked_equal(y,0) 

产生一个掩码数组,掩码是一个包含 10 个 False 值的数组,而

y = np.arange(1,10)  
yy = np.ma.masked_equal(y,0) 

生成一个掩码数组,掩码设置为标量 False。结果,鉴于在我的代码中我事先不知道掩码是否匹配数组中的任何条目,我不得不明确地检查:

yy=np.ma.masked_values(y,0) 
if np.isscalar(yy.mask): 
    yy.mask=np.zeros(y.shape,dtype=bool) 

这对我来说似乎工作过度了。这种行为的原因是什么,有没有办法避免这种情况?

请您参考如下方法:

您可以简单地自己创建MaskedArray:

yy = np.ma.MaskedArray(y, mask=(y==0)) 

NumPy 似乎试图在 MaskedArray 未屏蔽的情况下尽量减少内存需求并加快计算速度。

numpy.ma.nomask

Value indicating that a masked array has no invalid entry. nomask is used internally to speed up computations when the mask is not needed.

如果你检查:

>>> np.ma.nomask 
False 

因此单个 False 表示“无掩码”。所以你也可以检查 maskedarr.mask 是 np.ma.nomask (它是一个 garantueed constant ):

yy = some_operation_that_creates_a_masked_array 
if yy.mask is np.ma.nomask: 
    yy.mask = np.zeros(yy.shape, dtype=bool) 

它携带了比 np.isscalar 更多的上下文。