获取与 pandas GroupBy中的最大值对应的行 [英] Get the row corresponding to the max in pandas GroupBy

查看:65
本文介绍了获取与 pandas GroupBy中的最大值对应的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的DataFrame:

Simple DataFrame:

df = pd.DataFrame({'A': [1,1,2,2], 'B': [0,1,2,3], 'C': ['a','b','c','d']})
df
   A  B  C
0  1  0  a
1  1  1  b
2  2  2  c
3  2  3  d

我希望对A列的每个值( groupby )求C列的值B列最大。例如,对于A列的第1组,B列的最大值为1,所以我想要C列的值 b:

I wish for every value (groupby) of column A, to get the value of column C, for which column B is maximum. For example for group 1 of column A, the maximum of column B is 1, so I want the value "b" of column C:

   A  C
0  1  b
1  2  d

无需假设B列已排序,性能是重中之重,那么优雅。

No need to assume column B is sorted, performance is of top priority, then elegance.

推荐答案

检查 sort_values + drop_duplicates

df.sort_values('B').drop_duplicates(['A'],keep='last')
Out[127]: 
   A  B  C
1  1  1  b
3  2  3  d

这篇关于获取与 pandas GroupBy中的最大值对应的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆