Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset index on multilevel columns in pandas so that higher index perfaces lower index

Tags:

python

pandas

I have a df like:

df   a       b
     c   d   e  f 
1    .   .   .  .
2    .   .   .  .
3    .   .   .  .
4    .   .   .  .

and want this as the result:

 df  
       ac   ad  be  bf 
    1    .   .   .  .
    2    .   .   .  .
    3    .   .   .  .
    4    .   .   .  .
like image 839
wolfsatthedoor Avatar asked Feb 08 '23 14:02

wolfsatthedoor


2 Answers

df.columns.map("".join) is enough, as following:

In [12]: df
Out[12]: 
   A        B      
   C  D  E  F  G  H
0  0  1  2  3  4  5
1  0  1  2  3  4  5
2  0  1  2  3  4  5
3  0  1  2  3  4  5
4  0  1  2  3  4  5
5  0  1  2  3  4  5

In [13]: df.columns = df.columns.map("".join)

In [14]: df
Out[14]: 
   AC  AD  AE  BF  BG  BH
0   0   1   2   3   4   5
1   0   1   2   3   4   5
2   0   1   2   3   4   5
3   0   1   2   3   4   5
4   0   1   2   3   4   5
5   0   1   2   3   4   5
like image 152
Eastsun Avatar answered Mar 16 '23 00:03

Eastsun


You can use map and a zip/join over the column levels:

In [11]: df
Out[11]:
   a     b
   c  d  e  f
1  .  .  .  .
2  .  .  .  .
3  .  .  .  .
4  .  .  .  .

In [12]: df.columns.map(lambda x: "".join(*zip(*x)))
Out[12]: array(['ac', 'ad', 'be', 'bf'], dtype=object)

In [13]: df.columns = df.columns.map(lambda x: "".join(*zip(*x)))

In [14]: df
Out[14]:
  ac ad be bf
1  .  .  .  .
2  .  .  .  .
3  .  .  .  .
4  .  .  .  .
like image 36
Andy Hayden Avatar answered Mar 15 '23 23:03

Andy Hayden