当涉及无限值时,熊猫滚动返回NaN

时间:2020-03-19 22:52:57

标签: python python-3.x pandas

在包含rolling值的序列上使用inf时,即使操作定义得很好,如NaNmin,结果也包含max。例如:

import numpy as np
import pandas as pd

s = pd.Series([1, 2, 3, np.inf, 5, 6])
print(s.rolling(window=3).min())

这给出了:

0    NaN
1    NaN
2    1.0
3    NaN
4    NaN
5    NaN
dtype: float64

意料之中

0    NaN
1    NaN
2    1.0
3    2.0
4    3.0
5    5.0

计算序列的最小值可直接按预期进行:

s.min()  # 1.0

引入额外的NaN值的原因是什么?


Python 3.8.1,熊猫1.0.2

1 个答案:

答案 0 :(得分:5)

np.infpandas/core/window/rolling.py中被显式转换为np.NaN

# Convert inf to nan for C funcs
inf = np.isinf(values)
if inf.any():
    values = np.where(inf, np.nan, values)

How to represent inf or -inf in Cython with numpy?提供了有关他们为什么要这样做的信息。


如果您使用NaN而不是np.inf,则会发现完全相同的行为。由于min_counts会因为缺乏足够的观察力而将那些中间组扔掉,因此可能很难获得输出。一种干净的“破解方法”是将inf替换为您能获得的最大价值,这应该是相当安全的'min'

import numpy as np
s.replace(np.inf, np.finfo('float64').max).rolling(3).min()

#0    NaN
#1    NaN
#2    1.0
#3    2.0
#4    3.0
#5    5.0
#dtype: float64