问题描述
对于蒙版数组,我对numpy.median的输出有些困惑.这是一个简单的示例(假设导入了numpy-我的版本为1.6.2):
I'm a little confused about the output of numpy.median in the case of masked arrays. Here is a simple example (assuming numpy is imported - I have version 1.6.2):
>>> a = [3.0, 4.0, 5.0, 6.0, numpy.nan]
>>> am = numpy.ma.masked_array(a, [numpy.isnan(x) for x in a])
我希望能够在计算中位数时使用遮罩数组忽略数组中的nan
值.这可以使用掩蔽数组的numpy.mean
或mean()
方法获得均值:
I'd like to be able to use the masked array to ignore nan
values in the array when calculating the median. This works for mean using either numpy.mean
or the mean()
method of the masked array:
>>> numpy.mean(a)
nan
>>> numpy.mean(am)
4.5
>>> am.mean()
4.5
但是对于中位数,我得到了:
However for median I get:
>>> numpy.median(am)
5.0
但是我希望有更多类似的结果:
but I'd expect something more like this result:
>>> numpy.median([x for x in a if not numpy.isnan(x)])
4.5
,不幸的是masked_array
没有median
方法.
推荐答案
在MaskedArray
上使用np.ma.median
.
[说明:如果我没记错的话,np.median
不支持子类,因此它无法在np.ma.MaskedArray
上正常工作.]
[Explanation: If I remember correctly, the np.median
does not support subclasses, so it fails to work correctly on np.ma.MaskedArray
.]
这篇关于在掩码数组上使用numpy.median的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!