假设我有一个看起来像这样的数据框:
team_id player_id score
0 1 1 3
1 1 2 6
2 1 3 2
3 2 1 10
4 2 2 8
我想通过得分提取每支球队中顶级球员的排:
team_id player_id score
1 1 2 6
3 2 1 10
我该怎么做?熊猫是否有类似“窗口”的功能?
答案 0 :(得分:3)
尝试groupby
和idxmax
:
df.loc[df.groupby('team_id')['score'].idxmax()]
team_id player_id score
1 1 2 6
3 2 1 10
答案 1 :(得分:3)
sort_values
+ drop_duplicates
df.sort_values('score').drop_duplicates(['team_id'],keep='last')
Out[576]:
team_id player_id score
1 1 2 6
3 2 1 10
答案 2 :(得分:3)
您可以将transform
与groupby
和max
结合使用:
df[df['score'] == df.groupby('team_id')['score'].transform('max')]
team_id player_id score
1 1 2 6
3 2 1 10