Reputation: 10697
I have a df
that looks like this
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
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
c1 c2
0 87 33 32 34
1 32 10 45 62
2 78 83 99 71
Upvotes: 11
Views: 14446
Reputation: 862601
You can use list comprehension to select second-level values if c
:
df.columns = [col2 if col1 == 'c' else col1 for col1, col2 in df.columns]
print (df)
a b c1 c2
0 87 33 32 34
1 32 10 45 62
2 78 83 99 71
Previous solutions for old pandas versions:
I think you can use 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']
:
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
solution is remove []
or add parameter values='c'
if missing.
Upvotes: 8