使用 .melt() 重塑政府資料
美國勞工統計局(BLS)常以易讀的格式提供資料序列——每個月份各佔一個欄位,而每一年是一個不同的列。可惜的是,這種寬表格式不利於隨時間繪圖。在本練習中,你會使用 .melt() 將 BLS 的美國失業率資料表重塑為可用於繪圖的形式。你需要在資料表中新增一個日期欄位,並依該欄位排序,才能正確繪製圖表。
失業率資料已載入為名為 ur_wide 的資料表。建議你在開始作答前先探索此資料表。
本練習屬於課程
使用 pandas 進行資料表連接
練習說明
- 使用
.melt()將ur_wide中除了year以外的所有欄位反樞紐,並將月份與數值的欄位名稱分別設為month與unempl_rate。將結果儲存為ur_tall。 - 在
ur_tall中新增名為date的欄位,將year與month兩欄以 年-月 格式組合成較長的字串,然後轉換為日期型別。 - 依日期將
ur_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()