顯示移動平均
你也可以把時間序列中的數值畫成移動平均。這相當於對資料做「平滑化」,當時間序列含有大量雜訊或離群值時特別有用。對於給定的 DataFrame df,你可以使用以下指令取得時間序列的移動平均:
df_mean = df.rolling(window=12).mean()
window 參數應根據時間序列的粒度來設定。例如,若時間序列是每日資料,而你想計算整年期間的移動值,就應將參數設為 window=365。此外,也很容易為其他指標取得移動值,例如標準差(.std())或變異數(.var())。
本練習屬於課程
使用 Python 視覺化時間序列資料
練習說明
- 計算
co2_levels的 52 週移動平均,指定為ma。 - 計算
co2_levels的 52 週移動標準差,指定為mstd。 - 計算時間序列的上界,定義為 移動平均 +(2 × 移動標準差),指定為
ma[upper]。同樣地,計算下界為 移動平均 −(2 × 移動標準差),指定為ma[lower]。 - 繪製
ma的折線圖。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Compute the 52 weeks rolling mean of the co2_levels DataFrame
ma = ____.rolling(window=____).____()
# Compute the 52 weeks rolling standard deviation of the co2_levels DataFrame
mstd = ____
# Add the upper bound column to the ma DataFrame
ma['upper'] = ma['co2'] + (____ * ____)
# Add the lower bound column to the ma DataFrame
ma['lower'] = ma['co2'] - (____ * ____)
# Plot the content of the ma DataFrame
ax = ____(linewidth=0.8, fontsize=6)
# Specify labels, legend, and show the plot
ax.set_xlabel('Date', fontsize=10)
ax.set_ylabel('CO2 levels in Mauai Hawaii', fontsize=10)
ax.set_title('Rolling mean and variance of CO2 levels\nin Mauai Hawaii from 1958 to 2001', fontsize=10)
plt.show()