简体   繁体   English

分组并找到平均值并在不同的列上计数

[英]Groupby and find the mean and count on separate columns

I have the following data frame (df): 我有以下数据框(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'])

I think you're looking for groupby + agg passed as a dict . 我认为您正在寻找通过dict传递的groupby + agg

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM