我有一个多级 pandas 数据框,我正在尝试对其进行调平。我使用 reset_index 但它给我错误提示该名称已经存在。
我不想使用 reset_index(drop=True)
因为我想保留其中一个列名。
我想作为我的新数据框:
country,listing_neighborhood,count
现在,
df.columns
只给出 count
。
我的代码:
df.columns = ['count']
df.reset_index() -> gives error that `ValueError: cannot insert country, already exists`
我也试过:
df.columns.droplevel(0)
-> 给出错误 'Index' object has no attribute 'droplevel'
最佳答案
您需要删除第一个重复的级别:
df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'F':list('aaabbb')
})
df = (df.set_index(['A','F','C'])
.rename_axis(['country','country','listing_neighborhood'])
.rename(columns={'B':'count'}))
print (df)
count
country country listing_neighborhood
a a 7 4
b a 8 5
c a 9 4
d b 4 5
e b 2 5
f b 3 4
df = df.reset_index(level=0, drop=True).reset_index()
print (df)
country listing_neighborhood count
0 a 7 4
1 a 8 5
2 a 9 4
3 b 4 5
4 b 2 5
5 b 3 4
或者:
df = df.droplevel(0).reset_index()
关于python - Pandas 无法重置索引,因为名称存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48761486/