Unnikrishnan
Unnikrishnan

Reputation: 3313

Change column value alternatively based on the previous value in pandas

I have the following dataframe I'm trying to change the column value based on the previous signal, for example if the previous signal is BUY then next value should be a SELL otherwise it should be SKIP same way for the SELL signal also.

Imaging this as stock price so after BUY the signal must be SELL that's what i'm trying to do.

import pandas as pd
import numpy as np
data = {'Price':[3.4, 3.5, 3.2, 3.3, 3.2, 3.7, 4, 3.1, 3.4, 3.1],
        'Signal':['BUY', 'SELL', np.nan, 'BUY', 'BUY', 'SELL', np.nan, 'SELL', 'SELL', 'BUY']
}
df = pd.DataFrame(data)
df

output

0   3.4 BUY
1   3.5 SELL
2   3.2 NaN
3   3.3 BUY
4   3.2 BUY
5   3.7 SELL
6   4.0 NaN
7   3.1 SELL
8   3.4 SELL
9   3.1 BUY

I'm expecting an output like the following.

0   3.4 BUY
1   3.5 SELL
2   3.2 SKIP
3   3.3 BUY
4   3.2 SKIP
5   3.7 SELL
6   4.0 SKIP
7   3.1 SKIP
8   3.4 SKIP
9   3.1 BUY

I tried the following code but it didn't work as expected.

df.Signal = df.Signal.mask(df.Signal.shift(1) == df.Signal, 'SKIP')

How I can make it alternative BUY and SELL signal and everything else as SKIP?

Upvotes: 0

Views: 89

Answers (1)

gereleth
gereleth

Reputation: 2482

This should probably work

s = df.Signal.fillna(method='ffill')
df.loc[s==s.shift(),'Signal'] = 'SKIP'

Upvotes: 1

Related Questions