pandas 熊猫无法重置索引,因为名称存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48761486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:10:06  来源:igfitidea点击:

Pandas unable to reset index because name exist

pythonpandas

提问by jxn

I have a multi-level pandas dataframe which im trying to level. I use reset_index but its giving me error that the name already exist.

我有一个多级Pandas数据框,我正在尝试对其进行调整。我使用 reset_index 但它给了我名称已经存在的错误。

I dont want to use reset_index(drop=True)because i want to keep one of the column names still.

我不想使用,reset_index(drop=True)因为我想保留其中一个列名。

enter image description here

在此处输入图片说明

i want as my new dataframe:

我想作为我的新数据框:

country,listing_neighborhood,count

国家,listing_neighborhood,计数

right now,

马上,

df.columnsonly gives count.

df.columns只给count.

my code:

我的代码:

df.columns = ['count']
df.reset_index() -> gives error that `ValueError: cannot insert country, already exists`

I also tried:

我也试过:

df.columns.droplevel(0)-> gives error that 'Index' object has no attribute 'droplevel'

df.columns.droplevel(0)-> 给出错误 'Index' object has no attribute 'droplevel'

回答by jezrael

You need remove first duplicated level:

您需要删除第一个重复级别:

df = df.reset_index(level=0, drop=True).reset_index()

Or:

或者:

df.index = df.index.droplevel(0)
df = df.reset_index()

回答by Catbuilts

You can change the existing name so that it would not be duplicated anymore:

您可以更改现有名称,使其不再重复:

df.reset_index(name="new_name")

df.reset_index(name="new_name")

Hope this help

希望这有帮助