pandas 删除多索引级别但保留列的名称 - 熊猫

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44627970/
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 03:49:53  来源:igfitidea点击:

drop multiindex level but keep names of columns - pandas

pythonpandasmulti-index

提问by HappyPy

I have a dfthat looks like this

我有一个df看起来像这样

   a     b      c
              c1  c2
0  87    33   32  34
1  32    10   45  62
2  78    83   99  71

I'd like to drop the clevel but keep all the other column names

我想降低c级别但保留所有其他列名称

   a     b    c1  c2
0  87    33   32  34
1  32    10   45  62
2  78    83   99  71

df.columns = df.columns.droplevel(0)works but the names of aand bdisappear

df.columns = df.columns.droplevel(0)有效,但名称ab消失

              c1  c2
0  87    33   32  34
1  32    10   45  62
2  78    83   99  71

采纳答案by jezrael

I think you can use set_index+ droplevel+ reset_index:

我想你可以使用set_index+ droplevel+ reset_index

df = df.set_index(['a','b'])
df.columns = df.columns.droplevel(0)
df = df.reset_index()
print (df)
    a   b  c1  c2
0  87  33  32  34
1  32  10  45  62
2  78  83  99  71

Another solution with select columns by ['c']:

选择列的另一种解决方案['c']

df = df.set_index(['a','b'])['c'].reset_index()
print (df)
    a   b  c1  c2
0  87  33  32  34
1  32  10  45  62
2  78  83  99  71

But if get it from pivot_tablesolutionis remove []or add parameter values='c'if missing.

但是,如果从pivot_table解决方案中获取它,则删除[]或添加参数(values='c'如果丢失)。