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'])
cs95
  • 379,657
  • 97
  • 704
  • 746
sheldonzy
  • 5,505
  • 9
  • 48
  • 86
  • 2
    And see [Apply multiple functions to multiple groupby columns](https://stackoverflow.com/questions/14529838/apply-multiple-functions-to-multiple-groupby-columns) – Zero Sep 30 '17 at 10:31

1 Answers1

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
cs95
  • 379,657
  • 97
  • 704
  • 746