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
相关产品推荐
相关产品推荐

