python - 索引下降级别

标签 python pandas dataframe multiple-columns flatten

我从数据透视表中获得了以下结果,该结果与访问我的商店的客户等级计数有关。我使用“droplevel”方法将列标题展平为 1 层,如何对索引执行相同的操作?我想删除索引上方的“Grade”,以便列标题与“Store No_”处于同一级别。

enter image description here

最佳答案

看来您需要删除列名称:

df.columns.name = None

或者rename_axis :

df = df.rename_axis(None, axis=1)

示例:

df = pd.DataFrame({'Store No_':[1,2,3],
                   'A':[4,5,6],
                   'B':[7,8,9],
                   'C':[1,3,5],
                   'D':[5,3,6],
                   'E':[7,4,3]})
df = df.set_index('Store No_')
df.columns.name = 'Grade'
print (df)
Grade      A  B  C  D  E
Store No_               
1          4  7  1  5  7
2          5  8  3  3  4
3          6  9  5  6  3

print (df.rename_axis(None, axis=1))
           A  B  C  D  E
Store No_               
1          4  7  1  5  7
2          5  8  3  3  4
3          6  9  5  6  3

df = df.rename_axis(None, axis=1).reset_index()
print (df)
   Store No_  A  B  C  D  E
0          1  4  7  1  5  7
1          2  5  8  3  3  4
2          3  6  9  5  6  3

关于python - 索引下降级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41395569/

相关文章:

python - 将 2D 图像转换为 3D

r - table() 的 as.data.frame 总结频率

pandas - 将 Pandas 数据框中的所有单元格从 float64 数组展平为 int

python - [^.]* 在正则表达式中是什么意思?

python - 如何使用python识别硬链接(hard link)?

python - 在 python 2 上释放 C 扩展模块时运行函数

python - 使 python lambda func 在 Pandas Dataframe 中的 apply 方法内工作

python - 如何在不修改数据框的情况下同时按列和多索引的一部分对 pandas 数据框进行排序

python pandas 非唯一字典键

python - pandas diff() 为一阶差分给出 0 值,我想要实际值