Skip to content Skip to sidebar Skip to footer

Passing Argument In Groupby.agg With Multiple Functions

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 will ask my question using a built

Solution 1:

Use lambda function:

q = 0.22
df1 = df.groupby('lvl_1')['value'].agg(['min','max',lambda x: x.quantile(q)])
print (df1)
            minmax  <lambda>
lvl_1                              
di     0.2754010.5300000.294589
fi     0.0543630.8488180.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)
            minmax  custom_quantile
lvl_1                                     
di     0.2754010.5300000.294589
fi     0.0543630.8488180.136555

Solution 2:

df1 = df.groupby('lvl_1')['value'].agg(['min','max',("custom_quantile",lambda x: x.quantile(q))])

for q=0.22, the output is:

minmax         custom_quantile
lvl_1           
di     0.2754010.5300000.294589
fi     0.0543630.8488180.136555

Post a Comment for "Passing Argument In Groupby.agg With Multiple Functions"