【问题标题】:Median of a list with NaN values removed, in python在python中删除了NaN值的列表的中位数
【发布时间】:2014-10-20 21:38:17
【问题描述】:

是否可以在不显式删除 NaN 而是忽略它们的情况下计算列表的中位数?

我希望 median([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN]) 为 2,而不是 NaN。

【问题讨论】:

标签: python numpy pandas median


【解决方案1】:

numpy 1.9.0 有函数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

如果您不能使用 1.9.0 版的 numpy,类似@Parker 的回答会起作用;例如

>>> 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 的一元运算符表示法。)

【讨论】:

    【解决方案2】:

    我会清除所有 NaN 的列表,然后获取已清除列表的中位数。有两种方法浮现在脑海。如果你使用的是 numpy 库,你可以这样做:

    x = x[numpy.logical_not(numpy.isnan(x))] 其中x 是您想要获取中位数的列表

    或者,如果您只想使用包含的库,您可以这样做:

    import math
    x = [value for value in x if not math.isnan(value)]
    

    然后要获得中位数,只需使用清理后的列表:`median(x)``

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-21
      • 2021-12-22
      • 1970-01-01
      • 2020-09-23
      • 2018-05-01
      • 2015-04-16
      • 1970-01-01
      • 2020-10-19
      相关资源
      最近更新 更多