Merging a pandas groupby result back into DataFrame

后端 未结 2 1845
迷失自我
迷失自我 2021-02-19 23:41

I have a DataFrame that looks like this...

   idn value  
0  ID1    25
1  ID1    30
2  ID2    30
3  ID2    50

I want to add another column to t

2条回答
  •  醉话见心
    2021-02-20 00:01

    set the index of df to idn, and then use df.merge. after the merge, reset the index and rename columns

    dfmax = df.groupby('idn')['value'].max()
    
    df.set_index('idn', inplace=True)
    
    df = df.merge(dfmax, how='outer', left_index=True, right_index=True)
    
    df.reset_index(inplace=True)
    
    df.columns = ['idn', 'value', 'max_value']
    

提交回复
热议问题