2 回答
TA贡献1836条经验 获得超5个赞
你可以试试这个
p50 = df.groupby(['day','mealtype']).agg(p50 = ('oz',lambda x: x.quantile(0.5))).reset_index()
p90 = df.groupby(['day','mealtype']).agg(p90 = ('oz',lambda x: x.quantile(0.9))).reset_index()
new_df=p50.merge(p90, on=['day','mealtype'])
new_df
或者
new_df = df.groupby(['day','mealtype'])['oz'].agg(p50 = (lambda x: x.quantile(0.5)),
p90 = (lambda x: x.quantile(0.9))).reset_index()
输出
day mealtype p50 p90
0 Monday Dinner 0.210 0.290
1 Monday Snack 0.385 0.421
2 Sunday Dinner 0.010 0.010
3 Sunday Lunch 0.030 0.030
4 Sunday Snack 0.330 0.330
5 Tuesday Breakfast 0.100 0.100
6 Tuesday Dinner 0.090 0.090
TA贡献1871条经验 获得超8个赞
咱们试试吧groupby().quantile():
(df.groupby(['day','mealtype'])['oz']
.quantile(q=[0.5,0.9])
.unstack(level=-1)
.rename(columns=lambda x: f'p{int(x*100)}') # rename columns
)
输出:
p50 p90
day mealtype
Monday Dinner 0.210 0.290
Snack 0.385 0.421
Sunday Dinner 0.010 0.010
Lunch 0.030 0.030
Snack 0.330 0.330
Tuesday Breakfast 0.100 0.100
Dinner 0.090 0.090
添加回答
举报