繁体   English   中英

在pandas GroupBy中获取与max相对应的行

[英]Get the row corresponding to the max in pandas GroupBy

简单的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”:

   A  C
0  1  b
1  2  d

无需假设B列已排序,性能优先,然后优雅。

df.groupby('A').apply(lambda x: x.loc[x['B'].idxmax(), 'C'])
#    A
#1    b
#2    d

使用idxmax查找B最大的索引,然后在该组中选择C列(使用lambda函数)

检查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

这是groupbynlargest的一点乐趣:

(df.set_index('C')
   .groupby('A')['B']
   .nlargest(1)
   .index
   .to_frame()
   .reset_index(drop=True))

   A  C
0  1  b
1  2  d

或者, sort_valuesgroupbylast

df.sort_values('B').groupby('A')['C'].last().reset_index()

   A  C
0  1  b
1  2  d

与@Jondiedoop类似的解决方案,但避免apply

u = df.groupby('A')['B'].idxmax()

df.loc[u, ['A', 'C']].reset_index(drop=1)

   A  C
0  1  b
1  2  d

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM