Reshaping a multiindex pandas dataframe
Let's use stack
, swaplevel
and sort_index
:
df.stack(0).swaplevel(0,1).sort_index()
Output:
METRIC a b c d
ID
I 2015-08-01 0 1 2 3
2015-08-02 4 5 6 7
2015-08-03 8 9 10 11
II 2015-08-01 20 21 22 23
2015-08-02 24 25 26 27
2015-08-03 28 29 30 31
III 2015-08-01 40 41 42 43
2015-08-02 44 45 46 47
2015-08-03 48 49 50 51
You can let transpose
or T
do some of the work for you.
df.T.stack().unstack(1)
METRIC a b c d
ID
I 2015-08-01 0 1 2 3
2015-08-02 4 5 6 7
2015-08-03 8 9 10 11
II 2015-08-01 20 21 22 23
2015-08-02 24 25 26 27
2015-08-03 28 29 30 31
III 2015-08-01 40 41 42 43
2015-08-02 44 45 46 47
2015-08-03 48 49 50 51