测试Numpy MaskedArray实例均值的等价会引发属性错误

时间:2015-04-17 02:11:30

标签: python numpy

修改1:

到目前为止,似乎这是在版本1.8.1和1.9.2之间添加的错误。我还没有追查根本原因。在1.8.1 np.ma.MaskedArray.mean()中会返回一个标量。在1.9.2中,它返回零维MaskedArray。这似乎只有在foo.mask设置为np.ma.nomask时才会出现。

编辑2:

I have submitted this as a bug here.

我试图追踪这个问题,但是对MaskedArray.mean()的继承有困难。具体来说,我在numpy / core / fromnumeric.py中的第2711行遇到困难,当使用MaskedArray.mean()实例调用时,它似乎回调到MaskedArray

原始问题:

我可能在这里做了一些有趣的事情,但我似乎无法找到问题所在。当我测试两个不同np.ma.MaskedArray实例的均值的等价时,会引发AttributeError

创建数组:

In [1]: import numpy as np

In [2]: foo = np.ma.array([1,2,3,4])

In [3]: bar = np.ma.array([1,2,3,4])

In [4]: foo.mean()
Out[4]: 
masked_array(data = 2.5,
             mask = False,
       fill_value = 1e+20)


In [5]: bar.mean()
Out[5]: 
masked_array(data = 2.5,
             mask = False,
       fill_value = 1e+20)

数组的比较工作正常:

In [6]: foo == bar
Out[6]: 
masked_array(data = [ True  True  True  True],
             mask = False,
       fill_value = True)

测试平均值的等效性失败:

In [7]: foo.mean() == bar.mean()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-3b824b0972e3> in <module>()
----> 1 foo.mean() == bar.mean()

/users/___/.local/lib/python2.7/site-packages/numpy/ma/core.pyc in __eq__(self, other)
   3705                         mask = np.all([[f[n].all() for n in mask.dtype.names]
   3706                                         for f in mask], axis=axis)
-> 3707                 check._mask = mask
   3708         return check
   3709     #

AttributeError: 'numpy.bool_' object has no attribute '_mask'

In [8]: foo.mean() != bar.mean()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-0947fa5da1ed> in <module>()
----> 1 foo.mean() != bar.mean()

/users/___/.local/lib/python2.7/site-packages/numpy/ma/core.pyc in __ne__(self, other)
   3738                         mask = np.all([[f[n].all() for n in mask.dtype.names]
   3739                                         for f in mask], axis=axis)
-> 3740                 check._mask = mask
   3741         return check
   3742     #

测试更大或更小的均值可以正常工作:

AttributeError: 'numpy.bool_' object has no attribute '_mask'

In [9]: foo.mean() >= bar.mean()
Out[9]: 
masked_array(data = True,
             mask = False,
       fill_value = True)


In [10]: foo.mean() <= bar.mean()
Out[10]: 
masked_array(data = True,
             mask = False,
       fill_value = True)

Python版本2.7.2与Numpy版本1.9.2:

In [11]: np.__version__
Out[11]: '1.9.2'

np.ma.MaskedArray.__ne__()中,变量check似乎是由一行看似:

check = np.ndarray.__eq__(foo.filled(0), bar.filled(0)).view(type(foo))

我希望返回一个新的蒙版数组。但是,由于np.ndarray.__eq__()返回np.bool_的实例。尝试制作MaskedArray的{​​{1}}视图只会产生另一个check实例。例程尝试分配给np.bool_时发生错误,因为check._mask没有np.bool_属性。

有什么想法在这里发生了什么?我的错误或愚蠢?

0 个答案:

没有答案