Skip to content Skip to sidebar Skip to footer

Pandas Grouping - Values As Percent Of Grouped Totals Based On Another Column

This question is an extension of a question I asked yesterday, but I will rephrase Using a data frame and pandas, I am trying to figure out what the tip percentage is for each cate

Solution 1:

You can use apply to loop through rows of the data frame (with axis = 1), where for each row you can access the tip and total_bill and divide them to get the percentage:

(df.groupby(['sex', 'smoker'])[['total_bill','tip']].sum()
   .apply(lambda r: r.tip/r.total_bill, axis = 1))

#sex     smoker
#Female  No        0.153189
#        Yes       0.163062
#Male    No        0.157312
#        Yes       0.136919
#dtype: float64

Post a Comment for "Pandas Grouping - Values As Percent Of Grouped Totals Based On Another Column"