Python 的時間序列資料機器學習
Chris Holdgraf
Fellow, Berkeley Institute for Data Science
print(df)
df
0 0.0
1 1.0
2 2.0
3 3.0
4 4.0
# 將 DataFrame/Series 往過去偏移 3 個索引值
print(df.shift(3))
df
0 NaN
1 NaN
2 NaN
3 0.0
4 1.0
# data 是一個包含時間序列資料的 pandas Series
data = pd.Series(...)
# 偏移量
shifts = [0, 1, 2, 3, 4, 5, 6, 7]
# 建立時間位移資料的字典
many_shifts = {'lag_{}'.format(ii): data.shift(ii) for ii in shifts}
# 轉為 DataFrame
many_shifts = pd.DataFrame(many_shifts)
# 使用這些輸入特徵來擬合模型
model = Ridge()
model.fit(many_shifts, data)
# 視覺化已擬合模型的係數
fig, ax = plt.subplots()
ax.bar(many_shifts.columns, model.coef_)
ax.set(xlabel='Coefficient name', ylabel='Coefficient value')
# 設定格式讓圖表更清楚
plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment='right')


Python 的時間序列資料機器學習