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
drop multiindex level but keep names of columns - pandas
提问by HappyPy
I have a df
that 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 c
level 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 a
and b
disappear
df.columns = df.columns.droplevel(0)
有效,但名称a
和b
消失
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_table
solutionis remove []
or add parameter values='c'
if missing.
但是,如果从pivot_table
解决方案中获取它,则删除[]
或添加参数(values='c'
如果丢失)。