我想按两列对数据帧进行分组,然后在这些组中对聚合的结果进行排序。
In [167]: df
Out[167]:
count job source
0 2 sales A
1 4 sales B
2 6 sales C
3 3 sales D
4 7 sales E
5 5 market A
6 3 market B
7 2 market C
8 4 market D
9 1 market E
In [168]: df.groupby(['job','source']).agg({'count':sum})
Out[168]:
count
job source
market A 5
B 3
C 2
D 4
E 1
sales A 2
B 4
C 6
D 3
E 7
我现在想在每个组中按降序对“count”列排序,然后只取前三行。得到类似这样的东西:
count
job source
market A 5
D 4
B 3
sales E 7
C 6
B 4