a_g*_*est 8 python python-3.x pandas
在rolling包含inf值的系列上使用时,NaN即使操作定义明确,结果也会包含,例如min或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())
Run Code Online (Sandbox Code Playgroud)
这给出:
0 NaN
1 NaN
2 1.0
3 NaN
4 NaN
5 NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)
虽然我期待
0 NaN
1 NaN
2 1.0
3 2.0
4 3.0
5 5.0
Run Code Online (Sandbox Code Playgroud)
计算系列的最小值直接按预期工作:
s.min() # 1.0
Run Code Online (Sandbox Code Playgroud)
NaN引入附加值的原因是什么?
Python 3.8.1,熊猫 1.0.2
np.infnp.NaN在pandas/core/window/rolling.py 中显式转换为
# Convert inf to nan for C funcs
inf = np.isinf(values)
if inf.any():
values = np.where(inf, np.nan, values)
Run Code Online (Sandbox Code Playgroud)
如何用 numpy 在 Cython 中表示 inf 或 -inf?提供有关为什么他们必须这样做的信息。
如果你有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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |