Home > database >  Python Dataframe conditionally add value to existing column
Python Dataframe conditionally add value to existing column

Time:10-04

I'm having trouble to make my basic trading bot. I've managed to create the column buy/sell for the rows to buy or sell (https://i.stack.imgur.com/e7vg4.jpg) to select the rows I use:

  df.loc[df['Buy/Sell'] == 'Buy']

But now for these rows I want to add the df['Open'] value to the df['portfolio']

I tried the following:

 df.loc[(df['Buy/Sell'] == 'Sell'),'Portfolio'] = df['Portfolio']   df['Open']

It turned out it didn't select anything and just did this to all rows I hope someone can help me, thanks in advance

CodePudding user response:

This might be what you require:

df.loc[df['Buy/Sell'] == 'Sell', 'Portfolio'] = df['Portfolio'].add(df['Open'])

Please consider rewriting your code to the above.

  • Related