python - Pandas 无法重置索引,因为名称存在

标签 python pandas

我有一个多级 pandas 数据框,我正在尝试对其进行调平。我使用 reset_index 但它给我错误提示该名称已经存在。

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

enter image description here

我想作为我的新数据框:

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/

相关文章:

python - 打印语句仅出现在子进程调用之前或之后

python - 用户站点中使用的 Django 管理更改 ListView

python - 如何从具有频率计数的值创建数据框列?

python - 如何将 Python Pandas 列中的 '2+3' 之类的值转换为其聚合值

python - 使用 Pandas 按多列值对不同行的列表进行分组

Python:lambda 表达式的数据帧错误

python - Django - 保持原始方法的工作并添加新的自定义验证

python - 忽略在库中抛出和捕获的异常

python - 无法理解该函数中的关键逗号

python - 迭代多个dat文件,更新并作为单独的文件保存在单独的目录中