Extract row with maximum value in a group pandas dataframe

前端 未结 3 628
不知归路
不知归路 2020-12-04 16:05

A similar question is asked here: Python : Getting the Row which has the max value in groups using groupby

However, I just need one record per group even if there ar

3条回答
  •  死守一世寂寞
    2020-12-04 16:28

    Playing off of Roman Pekar's answer, I found that that the following code would work:

    from math import isnan
    df.iloc[[int(x) for x in df.groupby(by=df.Mt).apply(lambda x: x['count'].idxmax()).values if not isnan(y)]]
    

    Note the isnan condition, as my application had some nan entries in the column we are maximizing over.

提交回复
热议问题