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


- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01