如何在 Python 中的滚动平均计算中忽略 NaN [英] How to ignore NaN in rolling average calculation in Python

查看:297
本文介绍了如何在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆