【问题标题】:How to get the max value of a multiple column group-by pandas?如何通过熊猫获得多列分组的最大值?
【发布时间】:2014-11-06 21:42:04
【问题描述】:

我正在尝试根据 groupby 的另一列获取具有最大值的行,我正在尝试遵循此处给出的解决方案 Python : Getting the Row which has the max value in groups using groupby,但是当您申请时它不起作用

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

我明白了

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

感谢您的帮助

【问题讨论】:

  • 只是一个想法,这会给你想要的吗:annotations.groupby(['bookid'], sort=False)['weight'].max()

标签: python pandas group-by


【解决方案1】:

如果您需要最大重量的 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()
    

    【讨论】:

      【解决方案3】:

      分组后,我们可以将聚合函数作为 agg 函数中的字典传递给分组对象。

      annotations.groupby('bookid').agg({'weight': ['max']})
      

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 2021-12-12
        • 2019-07-06
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 2022-11-02
        • 2017-02-16
        相关资源
        最近更新 更多