始める無料で始める

月次トレンドと年次トレンドをプロットする

第2章で見たように、DataFrame のインデックスが datetime 型であれば、インデックス内の日・月・年を直接取り出せます。復習として、インデックス内の日付から年を取り出すには .index.year 属性を使います。その後、.groupby().mean() を使って、DataFrame 内の各時系列の年平均値を計算できます。

index_year = df.index.year
df_by_year = df.groupby(index_year).mean()

ここでは、学んだことを使って、jobs DataFrame に含まれる各時系列の集計平均値を表示していきます。

この演習はコースの一部です

Pythonで学ぶ時系列データの可視化

コースを見る

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Extract the month from the index of jobs
index_month = ____.____.____

# Compute the mean unemployment rate for each month
jobs_by_month = ____.____(____).____()

# Plot the mean unemployment rate for each month
ax = ____.plot(fontsize=6, linewidth=1)

# Set axis labels and legend
ax.set_xlabel('Month', fontsize=10)
ax.set_ylabel('Mean unemployment rate', fontsize=10)
ax.legend(bbox_to_anchor=(0.8, 0.6), fontsize=10)
plt.show()
コードを編集して実行