計算單一州的 D 值
在這個練習中,你會為 Georgia 州計算差異指數(Index of Dissimilarity)。請記住其公式為:
$$D = \frac{1}{2}\sum{\left\lvert \frac{a}{A} - \frac{b}{B} \right\rvert}$$
在這裡,A 組為白人(Whites),B 組為黑人(Blacks)。\(a\) 與 \(b\) 代表較小地理單位(普查分區,tracts)中的白人與黑人人口;\(A\) 與 \(B\) 則代表較大、包含性的地理範圍(Georgia,郵遞縮寫 = GA,FIPS 代碼 = 13)中的白人與黑人總人口。
pandas 已以慣用別名匯入,而包含 "white" 與 "black" 人口欄位的 tracts DataFrame 也已載入。
本練習屬於課程
使用 Python 分析美國 Census 資料
練習說明
- 建立新的 DataFrame
ga_tracts,只包含位於 Georgia 的 tracts("state"欄位需等於 FIPS 代碼"13")。 - 以清單提供欄位名稱(使用變數
w與b),印出 Georgia 中非西語白人與黑人的總數。 - 將各 tract 的白人人口除以白人總人口,再減去各 tract 的黑人人口除以黑人總人口;請使用變數
w與b讓程式碼更易讀。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define convenience variables to hold column names
w = "white"
b = "black"
# Extract Georgia tracts
ga_tracts = tracts[____]
# Print sums of Black and White residents of Georgia
print(ga_tracts[____].sum())
# Calculate Index of Dissimilarity and print rounded result
D = 0.5 * sum(abs(
____ / ____ - ____ / ____))
print("Dissimilarity (Georgia):", round(D, 3))