如何在pandas中进行多列分组并获取最大值?

8

我想要根据groupby的另一列获取具有最大值的行,我正在尝试按照这里给出的解决方案进行操作Python : Getting the Row which has the max value in groups using groupby,但是当你应用时它不起作用。

annotations.groupby(['bookid','conceptid'], sort=False)['weight'].max()

I get

bookid    conceptid
12345678  3942     0.137271
          10673    0.172345
          1002     0.125136
34567819  44407    1.370921
          5111     0.104729
          6160     0.114766
          200      0.151629
          3504     0.152793

但我只想获取最高权重的行,例如,

bookid    conceptid
12345678  10673    0.172345
34567819  44407    1.370921

我很感激您的帮助


1
只是一个想法,这个会给你想要的结果吗:annotations.groupby(['bookid'], sort=False)['weight'].max() - EdChum
3个回答

11

如果您需要获取最大权重的bookid和conceptid,请尝试以下方法

annotations.ix[annotations.groupby(['bookid'], sort=False)['weight'].idxmax()][['bookid', 'conceptid', 'weight']]

注意: 自Pandas v0.20起,ix已经被弃用。请使用.loc代替。


2

根据您的需求示例,我认为您的群组中有太多的内容。我认为您只需要:

annotations.groupby(['bookid'], sort=False)['weight'].max()

2
在分组之后,我们可以将聚合函数作为字典传递给分组对象中的agg函数。
annotations.groupby('bookid').agg({'weight': ['max']})

我认为在更新的版本中应该是annotations.groupby('bookid').agg(weight = 'max') - Imran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接