绘制按月和按年的趋势
正如我们在第 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()