gpt4 book ai didi

python - Numpy masked_array 总和

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:48 25 4
gpt4 key购买 nike

我希望对完全屏蔽的数组求和的结果为零,但返回的是“屏蔽”。如何让函数返回零?

>>> a = np.asarray([1, 2, 3, 4])
>>> b = np.ma.masked_array(a, mask=~(a > 2))
>>> b
masked_array(data = [-- -- 3 4],
mask = [ True True False False],
fill_value = 999999)

>>> b.sum()
7
>>> b = np.ma.masked_array(a, mask=~(a > 5))
>>> b
masked_array(data = [-- -- -- --],
mask = [ True True True True],
fill_value = 999999)


>>> b.sum()
masked
>>> np.ma.sum(b)
masked
>>>

还有一件意想不到的事:

>>> b.sum() + 3
masked

最佳答案

在你的最后一个案例中:

In [197]: bs=b1.sum()
In [198]: bs.data
Out[198]: array(0.0)
In [199]: bs.mask
Out[199]: array(True, dtype=bool)
In [200]: repr(bs)
Out[200]: 'masked'
In [201]: str(bs)
Out[201]: '--'

如果我指定keepdims,我会得到一个不同的数组:

In [208]: bs=b1.sum(keepdims=True)
In [209]: bs
Out[209]:
masked_array(data = [--],
mask = [ True],
fill_value = 999999)
In [210]: bs.data
Out[210]: array([0])
In [211]: bs.mask
Out[211]: array([ True], dtype=bool)

这是sum代码的相关部分:

def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}

_mask = self._mask
newmask = _check_mask_axis(_mask, axis, **kwargs)
# No explicit output
if out is None:
result = self.filled(0).sum(axis, dtype=dtype, **kwargs)
rndim = getattr(result, 'ndim', 0)
if rndim:
result = result.view(type(self))
result.__setmask__(newmask)
elif newmask:
result = masked
return result
....

这是

 newmask = np.ma.core._check_mask_axis(b1.mask, axis=None)
...
elif newmask: result = masked

在您的案例中产生 masked 值的行。 newmask 在所有值都被屏蔽的情况下为 True,而一些没有屏蔽则为 False。返回 np.ma.masked 的选择是经过深思熟虑的。

计算的核心是:

In [218]: b1.filled(0).sum()
Out[218]: 0

其余代码决定是返回标量还是掩码数组。

============

还有你的补充:

In [232]: np.ma.masked+3
Out[232]: masked

看起来 np.ma.masked 是一个特殊的数组,可以在计算中传播自身。有点像 np.nan

关于python - Numpy masked_array 总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com