依通勤方式的旅行時間熱度圖
在這個練習中,你會建立全國資料的熱度圖,用來比較通勤時間(分鐘)與交通方式。你從 data_row 開始,這是一個來自 JSON API 回應物件、僅含單一資料列的值清單。已建立並在主控台列印 5 種旅行 modes 與 9 個通勤 times 的清單。你需要把這筆單列資料重塑為「清單的清單」,建立可供傳入 sns.heatmap 的 DataFrame,並繪製熱度圖。
這筆資料列包含 5 種交通方式,每種方式對應一組含 9 個通勤時間的資料。一個 iteration 指的是一整組通勤時間。
已使用慣用別名載入 pandas 與 seaborn。
本練習屬於課程
使用 Python 分析美國 Census 資料
練習說明
- 將
iter_len設為times清單的長度。 - 在列表生成式中,建立一個 range,起始為 0,終止為
data_row的長度,步長為iter_len。 - 以
commutingDataFrame 作為第一個參數建立熱度圖;並在圖上標註以千為單位的通勤次數(使用整數除法除以1000)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Set iter_len to the number of commute times
iter_len = ____
# Break row into list of lists by travel mode
data = [data_row[i:i+iter_len] for i in range(____)]
# Create DataFrame, set data type to int
commuting = pd.DataFrame(data=data, index=modes, columns=times)
commuting = commuting.astype(int)
# Create heatmap of commuters by mode by income
sns.heatmap(____, annot=____, fmt = "d", cmap="YlGnBu")
plt.xticks(rotation = 50)
plt.yticks(rotation = 50)
plt.show()