Python – Convert multiple indexes of column names in one column

Convert multiple indexes of column names in one column… here is a solution to the problem.

Convert multiple indexes of column names in one column

I have this data frame

dt = pd. DataFrame({'At': ['A','B','C'], 
                   'R': ['27,0', '27,0', '27,0'], 
                   'V1': [0,0,0], 
                   'V2': [100,32,72], 'V3':[31,12,3]})

At     R  V1   V2  V3
0  A  27,0   0  100  31
1  B  27,0   0   32  12
2  C  27,0   0   72   3

Then I made a pivot table

dt.pivot_table(index='At', columns='R', 
               values=['V1','V2','V3']).reset_index()
  At   V1   V2   V3
R    27,0 27,0 27,0
0  A    0  100   31
1  B    0   32   12
2  C    0   72    3

I want to concatenate my multi-index column names like this

  At   27,0_V1   27,0_V2   27,0_V3
0  A       0       100        31
1  B       0        32        12
2  C       0        72         3

This is just an example, I have more than one level

Thanks

Solution

Handle the title a little; Use swaplevel + MultiIndex.map:

v = dt.pivot_table(index='At', columns='R', 
               values=['V1','V2','V3']).reset_index()

v.columns =  v.columns.swaplevel().map('_'.join).str.strip('_')

Or, as Scott Boston suggests

v.columns = v.columns.map('{0[1]}_{0[0]}'.format).str.strip('_')

v
  At  27,0_V1  27,0_V2  27,0_V3
0  A        0      100       31
1  B        0       32       12
2  C        0       72        3

Related Problems and Solutions