繪製每月與每年的趨勢
就像我們在第 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()