Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to groupby a given percentile?

I have a dataframe df

df
    User   City     Job             Age
0    A      x    Unemployed         33
1    B      x     Student           18
2    C      x    Unemployed         27
3    D      y  Data Scientist       28
4    E      y    Unemployed         45
5    F      y     Student           18

I want to groupby the City and do some stat. If I have to compute the mean, I can do the following:

tmp = df.groupby(['City']).mean()

I would like to do same by a specific quantile. Is it possible?

like image 296
emax Avatar asked May 13 '26 03:05

emax


1 Answers

def q1(x):
    return x.quantile(0.25)

def q2(x):
    return x.quantile(0.75)

fc = {'Age': [q1,q2]}
temp = df.groupby('City').agg(fc)
temp

       Age      
        q1    q2
City            
x     22.5  30.0
y     23.0  36.5
like image 148
warwick12 Avatar answered May 14 '26 18:05

warwick12



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!