-1

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
Marcus
  • 95
  • 9
  • Can you show how the desired result looks like? – joris Jan 25 '16 at 15:31
  • Does [this](http://stackoverflow.com/questions/20069009/pandas-good-approach-to-get-top-n-records-within-each-group) answer your question, or are you asking about the subsequent plotting question? – ako Jan 25 '16 at 15:40

1 Answers1

2

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
Sagar Waghmode
  • 767
  • 5
  • 16
  • Thanks, works perfect, funny the ,head needs to be after the groupby to create the correct cut – Marcus Jan 25 '16 at 17:47