unpivot MultiIndex DataFrame with pd.melt()

Viewed 1049

I would like to unpivot a DataFrame with MultiIndex columns, but I struggle to get the exact output I want. I played with all the parameters of the pd.melt() function but couldn't make it...

Here is the kind of input I have :

import pandas as pd
indexes = [['TC1', 'TC2'], ['x', 'z', 'Temp']]
data = pd.DataFrame(columns=pd.MultiIndex.from_product(indexes))

data.loc[0,('TC1', 'x')] = 10
data.loc[0,('TC1', 'z')] = 100
data.loc[0,('TC1', 'Temp')] = 250
data.loc[0,('TC2', 'x')] = 20
data.loc[0,('TC2', 'z')] = 200
data.loc[0,('TC2', 'Temp')] = 255

And here is the kind of output I would like, with "Time" column being the index of data

  Time   TC   x    z Temp
0    0  TC1  10  100  250
1    0  TC2  20  200  255

My real data have far more columns of kind TCx. Any clue?

2 Answers

Give this a try

data_out = data.stack(level=0).rename_axis(['Time','TC']).reset_index()

Out[87]:
   Time   TC Temp   x    z
0     0  TC1  250  10  100
1     0  TC2  255  20  200
Related