简体   繁体   中英

Pandas Pivoting Dataframe

I have a dataframe as shown below, I would like to perform a pivot so that I can plot the top 3 countries GDP per year. So I need to pivot the datadrame in such a way that it returns me the the 3 Countries with the 3 highest GDP each year

Any ideas?

 Year  Country   GDP
 01    USA      100
 01    UK        80
 01    Japan     50
 01    China     75
 02    USA       90
 02    UK        65
 02    Japan     70
 02    China     80

Do you want something like this?

In [19]: df
Out[19]: 
   Year Country  GDP
0     1     USA  100
1     1      UK   80
2     1   Japan   50
3     1   China   75
4     2     USA   90
5     2      UK   65
6     2   Japan   70
7     2   China   80

In [20]: df.sort_values(['Year', 'GDP'], ascending=[True, False]).groupby('Year').head(3)
Out[20]: 
   Year Country  GDP
0     1     USA  100
1     1      UK   80
3     1   China   75
4     2     USA   90
7     2   China   80
6     2   Japan   70

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM