python - 在 python 中删除了 NaN 值的列表的中值

标签 python numpy pandas median

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

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

最佳答案

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

如果您不能使用 numpy 的 1.9.0 版,@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

(当应用于 bool 数组时,~not 的一元运算符符号。)

关于python - 在 python 中删除了 NaN 值的列表的中值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475384/

相关文章:

python - Pytorch 通过知识转移保存和加载 VGG16

python - 如何将包含 '_' 的 JSON 字段拆分为子对象?

python - Selenium:闲置几分钟后为 "Unable to find session with ID"

python - 用于稀疏矩阵计算的 Scipy 或 Pandas?

python - Pandas 元组 groupby 聚合

python - 根据另一个数据框中的值生成一个新列

python - 在python中格式化输出

python - 插值到特定时间

pandas - Matplotlib::不显示所有 x 轴数据框变量

python - Pandas .min() 方法似乎不是最快的