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

Pandas调用reset_index()报错ValueError: cannot insert Country, already exists

按Country分组统计的ValueError问题解决

错误原因

你编写的代码中,groupby('Country')已将Country设为结果的索引,但你同时把Country列加入了要聚合的列列表中。执行sum()后,结果的列里会保留Country,再调用reset_index()时,系统会尝试将索引的Country转为列,此时列名重复,触发ValueError: cannot insert Country, already exists。

可行解决方案

以下两种方式都能实现按Country分组统计的需求:

方案1:移除聚合列中的Country,通过reset_index还原分组列

df2 = df.groupby('Country')[['Confirmed','Deaths','Recovered']].sum().reset_index()

方案2:使用as_index=False参数,直接保留分组列为普通列

df2 = df.groupby('Country', as_index=False)[['Confirmed','Deaths','Recovered']].sum()

两种方案最终都会生成以Country为普通列,对应各统计字段总和的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:03:24