【问题标题】:Get the row corresponding to the max in pandas GroupBy [duplicate]获取 pandas GroupBy 中最大值对应的行 [重复]
【发布时间】:2023-01-25 18:27:00
【问题描述】:

简单数据框:

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 列已排序,性能是重中之重,然后才是优雅。

【问题讨论】:

    标签: python pandas dataframe group-by pandas-groupby


    【解决方案1】:

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

    【讨论】:

    • 这令人印象深刻,我不得不说。
    • 根据timeit 接受这个答案,它比@coldspeed 快 0.0002 秒 [np.mean(timeit.repeat("df.sort_values('B').drop_duplicates(['A'],keep='last')", number = 1, repeat = 100, globals = globals()))]
    • @GioraSimchoni 感谢您的公平考虑和时间安排!
    • 这太棒了!
    【解决方案2】:
    df.groupby('A').apply(lambda x: x.loc[x['B'].idxmax(), 'C'])
    #    A
    #1    b
    #2    d
    

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

    【讨论】:

      【解决方案3】:

      这是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
      

      【讨论】:

        【解决方案4】:

        与@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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-06
          • 2021-11-04
          • 1970-01-01
          • 2018-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-03
          相关资源
          最近更新 更多