Pandas GroupBy and select rows with the minimum value in a specific column

前端 未结 2 1506
名媛妹妹
名媛妹妹 2021-02-19 02:36

I am grouping my dataset by column A and then would like to take the minimum value in column B and the corresponding value in column C.

data = pd.DataFrame({\'A\         


        
相关标签:
2条回答
  • 2021-02-19 03:06

    I feel like you're overthinking this. Just use groupby and idxmin:

    df.loc[df.groupby('A').B.idxmin()]
    
       A  B   C
    2  1  2  10
    4  2  4   4
    

    df.loc[df.groupby('A').B.idxmin()].reset_index(drop=True)
    
       A  B   C
    0  1  2  10
    1  2  4   4
    
    0 讨论(0)
  • 2021-02-19 03:20

    Had a similar situation but with a more complex column heading (e.g. "B val") in which case this is needed:

    df.loc[df.groupby('A')['B val'].idxmin()]
    
    0 讨论(0)
提交回复
热议问题