sheldonzy sheldonzy - 3 years ago 306
Python Question

pandas groupby - mean and count on different columns

I have the following data frame (df):

Items Category Quantity Weight(each)
Spoon Kitchen 2 0.7
Tent Shelter 1 80.0
Sleeping Bag Shelter 1 20.0
Sunscreen Health 2 5.0
Water Bottles Kitchen 2 35.0

I want to count the quantity of each category, and the mean of the weight by category.

The desired output:

count(Quantity) mean(Weight)
Kitchen 4 17.5
Shelter 2 50.0
Health 2 5.0

I know how to do it separately. But I'm not sure how to merge them together.



Answer Source

I think you're looking for groupby + agg passed as a dict.

df.groupby('Category').agg({'Quantity' : 'sum', 'Weight(each)' : 'mean'})

          Weight(each)  Quantity
Health            5.00         2
Kitchen          17.85         4
Shelter          50.00         2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download