在迴圈中計算 D
喬治亞州的差異指數為 0.544,算高還是低?我們把它拿來和芝加哥所在的伊利諾州(FIPS = 17)比較一下。
在這個練習中,你會用迴圈為「所有」州計算 $D$,然後比較喬治亞州與伊利諾州。
請記住,差異指數的公式是:
$$D = \frac{1}{2}\sum{\left\lvert \frac{a}{A} - \frac{b}{B} \right\rvert}$$
已經以慣用別名匯入了 pandas,並載入含有人口欄位 "white" 與 "black" 的 tracts DataFrame。變數 w 與 b 也已定義為欄位名稱 "white" 與 "black"。
本練習屬於課程
使用 Python 分析美國 Census 資料
練習說明
- 對
"state"欄位使用unique()方法,建立州別 FIPS 代碼的清單。 - 使用 for 迴圈,將
states的每個元素(也就是每個 FIPS 代碼)存入名為state的變數。 - 針對每個
state的值篩選tractsDataFrame,指派給tmp。 - 將公式套用到
tmp,為每個州計算 $D$,並把結果存入字典state_D。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Get list of state FIPS Codes
states = list(tracts["state"].____)
state_D = {} # Initialize dictionary as collector
for state in ____:
# Filter by state
tmp = ____
# Add Index of Dissimilarity to Dictionary
state_D[state] = 0.5 * sum(____)
# Print D for Georgia (FIPS = 13) and Illinois (FIPS = 17)
print("Georgia D =", round(state_D["13"], 3))
print("Illinois D =", round(state_D["17"], 3))