I attempt to apply a different formula to a new column "result" based on the column 'C' containing the condition. If C is 'add' then I would like to add X and Y. When C is 'mult' the result should be X * Y.
df = pd.DataFrame({'X': [0, 1, 2, 3, 4],
'Y': [5, 6, 7, 8, 9],
'C': ['add', 'add', 'mult', 'mult', 'mult']})
df['result'] = df['X'] * df['Y']
df.loc[df.C =='add', 'result'] = df.loc[df['C'] =='add', 'X'] \
+ df.loc[df['C'] =='add', 'Y']
df
The result I get is:
C X Y result
0 add 0 5 5
1 add 1 6 5
2 mult 2 7 14
3 mult 3 8 24
4 mult 4 9 36
What I need is 'result' in row 1 being 7
C X Y result
0 add 0 5 5
1 add 1 6 7
2 mult 2 7 14
3 mult 3 8 24
4 mult 4 9 36