開始使用免費開始

依州別計算各性別的人口百分比

在這個練習中,你將撰寫一個查詢,計算 2000 年女性在人口中所占的百分比,並依州別進行分組。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • sqlalchemy 匯入 casecastFloat
  • 定義一個查詢陳述式,選取 state 以及 2000 年女性的百分比。
    • func.sum() 裡,使用 case() 依據 sex 欄位從 pop2000 中選取女性。若 sex 不是 'F',別忘了指定 else_=0
    • 若要取得百分比,將 2000 年的女性人數除以 2000 年的總人口。把作為除數的 census.columns.pop2000 轉換為 Float,再乘上 100。
  • state 對查詢進行分組。
  • 執行查詢並將結果儲存為 results
  • 逐筆列印 statepercent_female。這部分已為你寫好,直接送出答案即可看到結果。

動手互動練習

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

# import case, cast and Float from sqlalchemy
from sqlalchemy import ____, ____, ____

# Build a query to calculate the percentage of women in 2000: stmt
stmt = select([____,
    (func.sum(
        ____([
            (____ == 'F', ____)
        ], else_=0)) /
     cast(func.sum(____), ____) * 100).label('percent_female')
])

# Group By state
stmt = stmt.group_by(____)

# Execute the query and store the results: results
results = connection.execute(____).fetchall()

# Print the percentage
for result in results:
    print(result.state, result.percent_female)
編輯並執行程式碼