在python中删除了NaN值的列表的中位数 [英] Median of a list with NaN values removed, in python
本文介绍了在python中删除了NaN值的列表的中位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在不显式删除NaN的情况下计算列表的中位数,而是忽略它们?
Is it possible to calculate the median of a list without explicitly removing the NaN's, but rather, ignoring them?
我希望median([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN])
为2,而不是NaN.
I want median([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN])
to be 2, not NaN.
推荐答案
numpy 1.9.0具有功能nanmedian
:
numpy 1.9.0 has the function nanmedian
:
nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False)
Compute the median along the specified axis, while ignoring NaNs.
Returns the median of the array elements.
.. versionadded:: 1.9.0
例如
>>> from numpy import nanmedian, NaN
>>> nanmedian([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN])
2.0
如果您不能使用numpy的1.9.0版本,则类似@Parker的答案将起作用;例如
If you can't use version 1.9.0 of numpy, something like @Parker's answer will work; e.g.
>>> import numpy as np
>>> x = np.array([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN])
>>> np.median(x[~np.isnan(x)])
2.0
或
>>> np.median(x[np.isfinite(x)])
2.0
(应用于布尔数组时,~
是not
的一元运算符.)
(When applied to a boolean array, ~
is the unary operator notation for not
.)
这篇关于在python中删除了NaN值的列表的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文