Python Pandas: convert rows as column headers

I have the following framework:

Year Country medal no of medals 1896 Afghanistan Gold 5 1896 Afghanistan Silver 4 1896 Afghanistan Bronze 3 1896 Algeria Gold 1 1896 Algeria Silver 2 1896 Algeria Bronze 3 

I want like this.

 Year Country Gold Silver Bronze 1896 Afghanistan 5 4 3 1896 Algeria 1 2 3 

Stack / Unstack doesn't seem to work.

+24
source share
1 answer

You are 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 
+35
source

Source: https://habr.com/ru/post/1013876/


All Articles