始める無料で始める

移動平均を表示する

時系列の値に対して移動平均を可視化することも可能です。これはデータを「平滑化」することに相当し、ノイズや外れ値が多い時系列でとくに有効です。任意の 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()
コードを編集して実行