按性别与州计算人口百分比
在本练习中,您将编写查询来计算 2000 年女性占总人口的百分比。您将按州对结果进行分组。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 从
sqlalchemy导入case、cast和Float。 - 定义一条语句,选择
state和 2000 年的女性占比。- 在
func.sum()中,使用case()从pop2000中选择女性(使用sex列)。如果sex不是'F',请记得指定else_=0。 - 若要得到百分比,将 2000 年女性人数除以 2000 年总人口。将被除数
census.columns.pop2000转换为Float,然后再乘以 100。
- 在
- 按
state对查询分组。 - 执行查询,并将其保存为
results。 - 为每条记录打印
state和percent_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)