时间:2021-01-07 11:35:48 | 栏目:Python代码 | 点击:次
直接上例子。
import pandas as pd df = pd.DataFrame({'class':['a','a','b','b','a','a','b','c','c'],'score':[3,5,6,7,8,9,10,11,14]})
df:
class | score | |
---|---|---|
0 | a | 3 |
1 | a | 5 |
2 | b | 6 |
3 | b | 7 |
4 | a | 8 |
5 | a | 9 |
6 | b | 10 |
7 | c | 11 |
8 | c | 14 |
df.sort_values(['class','score'],ascending=[1,0],inplace=True) grouped = df.groupby(['class']).head(2)
grouped:
class | score | |
---|---|---|
5 | a | 9 |
4 | a | 8 |
6 | b | 10 |
3 | b | 7 |
8 | c | 14 |
7 | c | 11 |