Passing argument in groupby.agg with multiple functions

后端 未结 2 1480
心在旅途
心在旅途 2020-12-19 14:50

Anyone knows how to pass arguments in a groupby.agg() with multiple functions?

Bottom line, I would like to use it with a custom function, but I wi

相关标签:
2条回答
  • 2020-12-19 15:02
    df1 = df.groupby('lvl_1')['value'].agg(['min','max',("custom_quantile",lambda x: x.quantile(q))])
    

    for q=0.22, the output is:

           min      max         custom_quantile
    lvl_1           
    di     0.275401 0.530000    0.294589
    fi     0.054363 0.848818    0.136555
    
    0 讨论(0)
  • 2020-12-19 15:27

    Use lambda function:

    q = 0.22
    df1 = df.groupby('lvl_1')['value'].agg(['min','max',lambda x: x.quantile(q)])
    print (df1)
                min       max  <lambda>
    lvl_1                              
    di     0.275401  0.530000  0.294589
    fi     0.054363  0.848818  0.136555
    

    Or is possible create f function and set it name for custom column name:

    q = 0.22
    f = lambda x: x.quantile(q)
    f.__name__ = 'custom_quantile'
    df1 = df.groupby('lvl_1')['value'].agg(['min','max',f])
    print (df1)
                min       max  custom_quantile
    lvl_1                                     
    di     0.275401  0.530000         0.294589
    fi     0.054363  0.848818         0.136555
    
    0 讨论(0)
提交回复
热议问题