How to ignore NaN in rolling average calculation in Python(如何在 Python 的滚动平均值计算中忽略 NaN)
问题描述
对于时间序列销售预测任务,我想创建一个表示过去 3 天平均销售额的特征.当我想预测未来几天的销售额时,我遇到了问题,因为这些数据点没有销售数据(NaN 值).Pandas 提供 rolling_mean(),但是当窗口中的任何数据点为 NaN 时,该函数会导致 NaN 输出.
For a time series sales forecasting task I want to create a feature that represents the average sales over the last 3 days. I have a problem when I want to predict the sales for days in the future, since these data points do not have sales data (NaN values). Pandas offers rolling_mean(), but that function results in a NaN ouput when any data point in the window is NaN.
我的数据:
Date Sales
02-01-2013 100.0
03-01-2013 200.0
04-01-2013 300.0
05-01-2013 200.0
06-01-2013 NaN
使用窗口为 2 的 pd.rolling_mean() 后的结果:
Result after using pd.rolling_mean() with window of 2:
Date Rolling_Sales
02-01-2013 NaN
03-01-2013 150.0
04-01-2013 250.0
05-01-2013 250.0
06-01-2013 NaN
想要的结果:
Date Rolling_Sales
02-01-2013 NaN
03-01-2013 150.0
04-01-2013 250.0
05-01-2013 250.0
06-01-2013 200.0
因此,如果包含 NaN,我想忽略它并取窗口中所有其他数据点的平均值.
So in case the a NaN is included, I want to ignore it and take the average of all the other data points in the window.
推荐答案
这里正在添加 min_periods
s=df.Sales.rolling(window=2,min_periods=1).mean()
s.iloc[0]=np.nan
s
Out[1293]:
0 NaN
1 150.0
2 250.0
3 250.0
4 200.0
Name: Sales, dtype: float64
这篇关于如何在 Python 的滚动平均值计算中忽略 NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 的滚动平均值计算中忽略 NaN
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
