My input dataframe is;
Grp A B C
Men 10 15 20
Women 15 10 25
Baby 5 10 20
Men 3 8 25
Men 7 5 30
Baby 5 2 8
Women 10 6 3
How can i get this upper and lower fences for unique groups?
Desired Output is;
GRP Upper_A Lower_A Upper_B Lower_B Upper_C Lower_C
Men
Women
Baby
Could you please help me about this? PS: Upper and lower values are box and whisker values.
Use GroupBy.agg
with Series.quantile
, specify new columns names and then flatten MultiIndex by f-string
s:
df = df.groupby('Grp').agg([('Upper', lambda x: x.quantile(.75)),
('Lower',lambda x: x.quantile(.25))])
df.columns = [f"{b}_{a}" for a,b in df.columns]
print (df)
Upper_A Lower_A Upper_B Lower_B Upper_C Lower_C
Grp
Baby 5.00 5.00 8.0 4.0 17.0 11.0
Men 8.50 5.00 11.5 6.5 27.5 22.5
Women 13.75 11.25 9.0 7.0 19.5 8.5