0

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)
Category       
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. Separately:

df.groupby('Category')['Quantity'].agg(['count'])

df.groupby('Category')['Weight(each)'].agg(['mean'])
1

1 Answer 1

5

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

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

          Weight(each)  Quantity
Category                        
Health            5.00         2
Kitchen          17.85         4
Shelter          50.00         2
Sign up to request clarification or add additional context in comments.

1 Comment

Yes exactly. Thanks. I did not know about the dict. That's great :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.