Python Pandas: Convert Rows as Column headers [duplicate]
You're looking for pivot_table
:
In [11]: medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal')
In [12]: medals
Out[12]:
medal Bronze Gold Silver
Year Country
1896 Afghanistan 3 5 4
Algeria 3 1 2
and if you want to reorder the columns:
In [12]: medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)
Out[12]:
medal Gold Silver Bronze
Year Country
1896 Afghanistan 5 4 3
Algeria 1 2 3
Stack/ Unstack won't work until you have the desired column in your row/ column indexes. e.g. In simple words, Stack/ Unstack will bring the lowest level of column index to the lowest level of row index and vice versa.
So in your case, you can achieve the same results with stack/unstack by