如何总结系列对象中每个类别的值?

时间:2016-11-21 23:21:19

标签: python pandas data-science

我有这个DataFrame:

Backpacking equipment DataFrame

我需要做的是按Category列对DataFrame进行分组,然后使用函数计算每个类别的总权重。这就是我到目前为止所做的......

def multiply(group, quantity, weight):
  x = group[quantity]
  y = group[weight]

  return x * y

print(df.groupby('Category').apply(multiply, 'Quantity',  'Weight (oz.)'))

我得到的结果是

Quantity by weight

现在,如何根据结果Series对象的每个类别(,包,住所,睡眠等)总计总重量?

1 个答案:

答案 0 :(得分:1)

使用您的数据样本:

Item,Category,Quantity,Weight (oz.)
Sleeping Pad,Sleep,1,80.0
Sleeping Bag,Sleep,1,20.0
Spoon,Kitchen,1,0.87
Stove,Kitchen,1,20.0
Water Filter,Kitchen,1,1.8
Water Bottles,Kitchen,2,35.0

In [1]: df = pd.read_clipboard(sep=',', index_col=0)


In [2]: df.groupby('Category').apply(lambda x: (x['Quantity'] *x['Weight (oz.)']).sum())
Out[2]: 
Category
Kitchen     92.67
Sleep      100.00
dtype: float64