You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Pandas统计各国死亡人数?

统计每个国家死亡人数的正确实现

你的错误原因

你写的if survived_list == 0: 是把整个列表和0比较,这显然不对——列表和单个数值永远不会相等,所以会出现逻辑错误。你应该判断列表里的单个元素是否为0,但这种循环统计的方法效率很低,不如直接用Pandas的内置功能。

推荐的Pandas高效实现

直接利用Pandas的分组和筛选功能,代码简洁又高效:

方法1:筛选死亡记录后分组计数

# 筛选出所有死亡(survived=0)的行,按国家分组统计数量
death_by_country = df[df['survived'] == 0].groupby('country').size()
print(death_by_country)

方法2:统计总人数与存活人数,计算死亡数

如果需要同时查看总人数、存活数和死亡数,可以这么写:

# 按国家分组,统计总人数和存活人数
country_stats = df.groupby('country')['survived'].agg(['count', 'sum'])
# 死亡数 = 总人数 - 存活人数
country_stats['death'] = country_stats['count'] - country_stats['sum']
# 只输出死亡数
print(country_stats['death'])

如果你想修正原来的循环写法(不推荐)

如果只是想理解循环逻辑,把你的代码改成这样就行:

# 用字典存每个国家的死亡人数
death_count = {}

countries_list = list(df['country'])
survived_list = list(df['survived'])

for i in range(len(survived_list)):
    # 判断当前是否是死亡记录
    if survived_list[i] == 0:
        country = countries_list[i]
        # 更新字典里的计数,不存在则初始化为0再加1
        death_count[country] = death_count.get(country, 0) + 1

# 打印结果
for country, count in death_count.items():
    print(f'{country}: {count}')

注意事项

  • 确保survived列是数值类型,如果替换后还是字符串,先转类型:df['survived'] = df['survived'].astype(int)
  • Pandas的groupby方法比手动循环快得多,2000行数据虽然循环也能跑,但数据量变大后差距会很明显

内容的提问来源于stack exchange,提问作者VB666

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:35:18