本文介绍了在掩码数组上使用numpy.median的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于蒙版数组,我对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.meanmean()方法获得均值:

I'd like to be able to use the masked array to ignore nanvalues 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 11:41