here is my dataframe:
df = [{'id': 1, 'name': 'bob', 'apple': 45, 'grape': 10, 'rate':0},
{'id': 1, 'name': 'bob', 'apple': 45, 'grape': 20, 'rate':0},
{'id': 2, 'name': 'smith', 'apple': 5, 'grape': 30, 'rate':0},
{'id': 2, 'name': 'smith', 'apple': 10, 'grape': 40, 'rate':0}]
i would like to: where apple= apple.sum() and grape=grape.sum() and rate = grape/apple*100.
id name apple grape rate
0 1 bob 90 30 300
1 2 smith 15 70 21.4
I have attempted this with the following:
df = pd.DataFrame(df)
def cal_rate(rate):
return df['apple'] / df['grape']*100
agg_funcs = {'apple':'sum',
'grape':'sum',
'rate' : cal_rate}
df=df.groupby(['id','name').agg(agg_funcs).reset_index()
But got this result:
id name apple grape rate
0 1 bob 90 30 105
1 2 smith 15 70 105
Can you help me out?thanks in advance.