時間序列——滑動窗口

滑動窗口是什麼?

滑動窗口就是能夠根據指定的單位長度框住時間序列,從而計算框內的統計指標。相當於一個長度指定的滑塊正在刻度尺上面滑動,每滑動一個單位即可反饋滑塊內的數據。

看個例子

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()

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章