Pandas 和移动平均线

Pandas and moving average

我有数据:

date        count
2015-09-01  5
2015-09-02  4
2015-09-03  8
2015-09-04  8
2015-09-05  3
2015-09-06  5
2015-09-07  9
2015-09-08  7
2015-09-09  5
2015-09-10  7
...

我需要获取过去 5 天的移动平均线

如何在 python 和 pandas 上完成?

你想要的IIUCrolling_mean:

In [136]:

df.set_index('date', inplace=True)
pd.rolling_mean(df['count'], window=5)
Out[136]:
date
2015-09-01    NaN
2015-09-02    NaN
2015-09-03    NaN
2015-09-04    NaN
2015-09-05    5.6
2015-09-06    5.6
2015-09-07    6.6
2015-09-08    6.4
2015-09-09    5.8
2015-09-10    6.6
dtype: float64

对于 pandas v0.22.0,您可以使用 rolling

df.rolling(5).mean()