Pandas 当有多个组时,选择n个最大值

Pandas 当有多个组时,选择n个最大值,pandas,Pandas,我想根据列数和年份选择前2个条目 比如 test= pd.DataFrame({'Year':['2016','2016','2016','2017','2017','2017'] ,'Country' : ['NL','GR','AU','NL','GB','BR'] ,'Count' : ['100','200','5','1000','2000','3']}) df; Year Country

我想根据列数和年份选择前2个条目

比如

test= pd.DataFrame({'Year':['2016','2016','2016','2017','2017','2017']
                    ,'Country' : ['NL','GR','AU','NL','GB','BR']
                    ,'Count' : ['100','200','5','1000','2000','3']}) 
df;

    Year    Country Count
0   2016    NL      100
1   2016    GR      200
2   2016    AU      5
3   2017    NL      1000
4   2017    GB      2000
5   2017    BR      3

因此,每年我都想看到排名前两位的国家。有什么想法吗?

首先需要将列
计数
转换为整数,然后最后使用或:

如果要在
计数
列中更改订单:

test['Count'] = test['Count'].astype(int)
df = test.sort_values(['Year','Count']).groupby('Year').tail(2)
print (df)
   Year Country  Count
0  2016      NL    100
1  2016      GR    200
3  2017      NL   1000
4  2017      GB   2000
可能重复的
test['Count'] = test['Count'].astype(int)
df = test.sort_values(['Year','Count']).groupby('Year').tail(2)
print (df)
   Year Country  Count
0  2016      NL    100
1  2016      GR    200
3  2017      NL   1000
4  2017      GB   2000
test['Count'] = test['Count'].astype(int)
df = test.sort_values(['Year','Count'], ascending=[True, False]).groupby('Year').head(2)
print (df)
   Year Country  Count
1  2016      GR    200
0  2016      NL    100
4  2017      GB   2000
3  2017      NL   1000