滑动窗口是什么?
滑动窗口就是能够根据指定的单位长度来框住时间序列,从而计算框内的统计指标。相当于一个长度指定的滑块正在刻度尺上面滑动,每滑动一个单位即可反馈滑块内的数据。
看个例子
import numpy as np
import pandas as pd
#时间序列ts
sales= pd.read_csv(r'G:\kaggle\FutureSales\sales_train.csv')
ts= sales.groupby(["date_block_num"])['item_cnt_day'].sum()#月销量
ts= pd.Series(ts)
print(ts[:10])
date_block_num
0 131479.0
1 128090.0
2 147142.0
3 107190.0
4 106970.0
5 125381.0
6 116966.0
7 125291.0
8 133332.0
9 127541.0
Name: item_cnt_day, dtype: float64
指定一个该序列单位长度为10的滑块:
r= ts.rolling(window=10)#Rolling [window=10,center=False,axis=0]
统计滑块内的均值、方差、标准差中位数、和等:
r.mean(), r.var(), r.std(), r.median(), r.skew()
print(r.mean().head(20))
date_block_num
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 124938.2
10 124791.2
11 130316.4
12 127292.1
13 127541.8
14 128374.5
15 125492.0
16 123574.4
17 120788.2
18 116583.0
19 114101.0
Name: item_cnt_day, dtype: float64
2017-10-10处为前10个值的平均值,也即是滑窗开始时候,滑块内的统计指标。
原始序列图:
import matplotlib.pyplot as plt
plt.figure(figsize=(16,5))
plt.plot(ts)
plt.show()
采用长度为12的滑窗后的统计指标——均值、标准差情况图:
plt.figure(figsize=(16,5))
plt.plot(ts.rolling(window=12).mean(), label='Rolling Mean')
plt.plot(ts.rolling(window=12).std(), label='Rolling Std')
plt.legend()
plt.show()