I am trying to sum values in a column by
groupby
df
id memo amount
1 pos 1.0
1 pos 2.0
1 neg 3.0
2 pos 4.0
2 pos 5.0
2 neg 6.0
2 neg 7.0
id
amount
memo
pos
neg
groupby
1
-1.0 - 2.0 + 3.0 = 0
df.groupby('id')['amount'].sum()
id
amount
memo
id memo amount total_amount
1 pos 1.0 0.0
1 pos 2.0 0.0
1 neg 3.0 0.0
2 pos 4.0 -4.0
2 pos 5.0 -4.0
2 neg 6.0 -4.0
2 neg 7.0 -4.0
Splitting the operation in two steps, you can achieve what you want through
df['temp'] = np.where(df.memo == 'pos', df.amount, -df.amount)
df['total_amount'] = df.groupby('id').temp.transform(sum)