Reset index on multi-level columns in pandas so that a higher index decreases the index

I have a df, for example:

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

and as a result we get the following:

 df  
       ac   ad  be  bf 
    1    .   .   .  .
    2    .   .   .  .
    3    .   .   .  .
    4    .   .   .  .
+4
source share
2 answers

df.columns.map("".join) enough as below:

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
+4
source

You can use map and zip / join by column level:

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  .  .  .  .
+4
source

Source: https://habr.com/ru/post/1615522/


All Articles