ZIP Code Tabulation Areas
在行銷領域,常常需要了解 ZIP Code 的人口結構。ZIP Code Tabulation Areas(「ZCTA」)是以普查區塊組成、由普查局定義的 ZIP Code 對應區域。在這個練習中,你將要求取得阿拉巴馬州所有 ZCTA 的總人口。
在 pandas 中,可以用索引來擷取特定列。GEOID 很適合作為列的識別碼。這個練習中,你會根據每一列的州與 ZCTA 設定多層索引。
requests 與 pandas 套件都已匯入。base_url 已定義,predicates 字典也已包含要請求的變數清單。
本練習屬於課程
使用 Python 分析美國 Census 資料
練習說明
- 在
predicates字典中設定"for"鍵以回傳「所有」ZCTA;請將地理層級完整拼寫為"zip code tabulation area (or part)" - 在
predicates字典中設定"in"鍵以只回傳阿拉巴馬州(Alabama)內的 ZCTA;你需要到先前學過的線上來源查找阿拉巴馬州的 FIPS 代碼 - 將 DataFrame 的索引設為
state與zcta欄位的串接。使用inplace = True以「不要」建立新的 DataFrame。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build dictionary of predicates and execute the request
predicates = {}
predicates["get"] = ",".join(["NAME", "P001001"])
____
____
r = requests.get(base_url, params=predicates)
# Construct the DataFrame
col_names = ["name", "total_pop", "state", "zcta"]
zctas = pd.DataFrame(columns=col_names, data=r.json()[1:])
zctas["total_pop"] = zctas["total_pop"].astype(int)
# Set multilevel index from GEOIDs and print the head
zctas.set_index([____, ____], inplace = True)
print(zctas.head())