2016-11-21 51 views
1

我有這個數據幀:如何總結系列對象中每個類別的值?

Backpacking equipment DataFrame

我需要做的是一羣以Category列數據框,然後用一個函數由每個類別計算總重量。這是我到目前爲止已經完成了...

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對象?

+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