cryptoref February 2016

Transpose multilevel index pandas

I need to transpose a dataframe from

Month  Year   Count
1      2013   4456
       2014   3321
       2015   3316
       2016   6798
2      2013   4123
       2014   4490
       2015   5689

and so on into one that looks like

Year   1     2
2013   4456  4123
2014   3321  4490
2015   3316  5689
2016   6798  NaN

various attempts, including looking at MultiLevel index to columns : getting value_counts as columns in pandas havent worked.

On edit - The unstack method didn't work (or i didn't know how to use it correctly) however the pivot with reset_index, works perfectly.

My first problem seems to be a total misunderstanding of indexes and multi indexes as Month Year are a multi-index (as per looking at the dataframe) but any attempts to index with df['Month'] or other combinations always fail.

Would really love some help here.

Answers


Jezzamon February 2016

The function you're looking for is pivot. You may need to use reset_index first.

df = df.reset_index().pivot('Year', 'Month', 'Count')

Alternatively, you can use the unstack function, as in this answer.

Post Status

Asked in February 2016
Viewed 3,457 times
Voted 13
Answered 1 times

Search




Leave an answer