Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop multiindex level but keep names of columns - pandas

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
like image 577
HappyPy Avatar asked Jun 19 '17 10:06

HappyPy


1 Answers

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.

like image 125
jezrael Avatar answered Oct 17 '22 05:10

jezrael