Shane Bruinen
Shane Bruinen

Reputation: 13

Python Dataframe conditionally add value to existing column

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.sstatic.net/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

Upvotes: 1

Views: 70

Answers (1)

sophocles
sophocles

Reputation: 13821

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.

Upvotes: 1

Related Questions