开始使用免费开始使用

使用 .melt() 重塑政府数据

美国劳工统计局(BLS)常以易读的形式提供数据序列——每个月单独一列,每一年为一行。可惜这种宽表格式不利于按时间绘图。在本练习中,您将把 BLS 的美国失业率数据用 .melt() 转换为便于绘图的长表格式。您需要为表格添加日期列,并按该列排序,才能正确绘图。

练习中已为您加载名为 ur_wide 的失业率数据表。建议您在开始前先探索一下该表。

本练习是课程的一部分

使用 pandas 连接数据

查看课程

练习说明

  • 使用 .melt()ur_wide 的所有列进行"反透视",但保留 year 不变;并将月份列与数值列的列名分别设为 monthunempl_rate。将结果保存为 ur_tall
  • ur_tall 中添加名为 date 的列,将 yearmonth 合并为"年-月"格式的长字符串,并将其转换为日期类型。
  • dateur_tall 排序,并保存为 ur_sorted
  • 使用 ur_sorted,以 unempl_rate 作为 y 轴、date 作为 x 轴进行绘图。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# unpivot everything besides the year column
ur_tall = ____


# Create a date column using the month and year columns of ur_tall
ur_tall['date'] = pd.to_datetime(ur_tall['____'] + '-' + ____)

# Sort ur_tall by date in ascending order
ur_sorted = ____

# Plot the unempl_rate by date
ur_sorted.plot(____)
plt.show()
编辑并运行代码