pandas groupby where you get the max of one column and the min of another column

前端 未结 1 451
旧巷少年郎
旧巷少年郎 2020-12-03 17:45

I have a dataframe as follows:

user    num1    num2
a       1       1
a       2       2
a       3       3
b       4       4
b       5       5
相关标签:
1条回答
  • 2020-12-03 18:32

    Use groupby + agg by dict, so then is necessary order columns by subset or reindex_axis. Last add reset_index for convert index to column if necessary.

    df = a.groupby('user').agg({'num1':'min', 'num2':'max'})[['num1','num2']].reset_index()
    print (df)
      user  num1  num2
    0    a     1     3
    1    b     4     5
    

    What is same as:

    df = a.groupby('user').agg({'num1':'min', 'num2':'max'})
                          .reindex_axis(['num1','num2'], axis=1)
                          .reset_index()
    print (df)
      user  num1  num2
    0    a     1     3
    1    b     4     5
    
    0 讨论(0)
提交回复
热议问题