为什么 np.percentile 对于高百分位数返回 NaN?

问题描述 投票:0回答:2

此代码:

print len(my_series)
print np.percentile(my_series, 98)
print np.percentile(my_series, 99)

给出:

14221  # This is the series length
1644.2  # 98th percentile
nan  # 99th percentile?

为什么 98 工作正常,但 99 却给出

nan

python numpy pandas
2个回答
20
投票

np.percentile 将 nan 视为非常高的数字。因此,高百分位数将在您最终得到 nan 的范围内。在您的情况下,1% 到 2% 的数据将是 nan(第 98 个百分位数将返回一个数字(实际上不是所有有效值的第 98 个百分位数),第 99 个百分位数将返回一个 nan)。

要计算没有 nan 的百分位数,可以使用 np.nanpercentile()

所以:

print(np.nanpercentile(my_series, 98))
print(np.nanpercentile(my_series, 99))

编辑: 在新的 Numpy 版本中,如果存在 nan,

np.percentile
将返回 nan,因此使这个问题变得显而易见。
np.nanpercentile
仍然有效。 `


0
投票

您可能在计算过程中遇到溢出,这可以解释为什么您在高百分位数处看到

NaN
。就我而言,我还在代码中遇到了
NaN
。为了解决这个问题,您可以使用
np.nanpercentile
,它可以更稳健地处理
NaN
值。

import numpy as np

# Example with NaNs in the data
data = np.array([1, 2, np.nan, 4, 5, 6])

# Calculate the 95th percentile, ignoring NaNs
percentile_95 = np.nanpercentile(data, 95)

print(f"95th percentile (ignoring NaNs): {percentile_95}")

此方法可确保数据集中的任何

NaN
值都被排除在百分位计算之外。如果您由于溢出或其他计算问题而遇到
NaN
,切换到
np.nanpercentile
应该会有所帮助。

了解更多信息:GitHub 评论。 感谢@Nick Chammas 的评论,强调了这一点。

© www.soinside.com 2019 - 2024. All rights reserved.