開始使用免費開始

州際人口流動

在影片中,你看過一張州際遷徙流量的熱圖,但畫面相當雜亂。這個練習中,你只會查看「中西部」地區內部的流動。

已載入一個 DataFrame state_to_state,其前幾列已顯示在主控台。回想影片中的說明:列標籤代表移入的州(moved to),欄名代表移出的州(moved from)。

清單 midwest_states 已定義為中西部各州的名稱。(如果想看看包含哪些州,可以將它列印到主控台。)這個 DataFrame 的欄名與索引也都是州名,因此你會用 midwest_states 來擷取此熱圖所需的欄與列。

pandasseaborn 已使用慣用別名匯入。

本練習屬於課程

使用 Python 分析美國 Census 資料

檢視課程

練習說明

  • 篩選資料框,只保留欄名在該州名清單中的欄,並只保留索引在該州名清單中的列。
  • 篩選後欄與列的順序可能被改變。請檢查 midwest.index 是否等於 midwest.columns
  • 依列索引(axis = 0)與欄名(axis = 1)排序 DataFrame。兩者皆使用 inplace = True
  • midwest 繪製熱圖。將色階設為黃-綠-藍漸層,使用 cmap="YlGnBu"

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Retain only rows and columns of Midwest states
midwest = state_to_state[____][state_to_state.index.isin(____)]

# Are rows and columns still in the same order?
print(____)

# Sort the rows (by index) and columns (by name)
midwest.sort_index(axis = ____, ____)
midwest.sort_index(axis = ____, ____)

# Create a heatmap of migration flows
____
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.show()
編輯並執行程式碼