Reputation: 75
Looking for advice please.
In my DF below, I would like to subract the 'difference' column value (red square), from the value in 'trailing sl' column (blue square), but shifted to lag .shift(1).
So the new values would be:
1.08778 - 0.00115
1.08663 - 0.00077
1.08586 - 0.00059
etc
I've tried .loc with a .shift value, but that's not quite right.
df.loc[df.difference != np.nan, 'trailing_sl'] = df.trailing_sl.shift(1) - df.difference
I'm stuck tbh.
Any advice on a route forward?
Upvotes: 0
Views: 129
Reputation: 75
FWIW, my answer was to make a cumulative sum series of the 'difference' column, and then subract the 'trailing_sl' value from the new series.
It seems to work, so far at least :)
Upvotes: 0
Reputation: 862591
Use Series.notna
:
m = df['difference'].notna()
df.loc[m, 'trailing_sl'] = df.trailing_sl.shift() - df['difference']
Or:
df['trailing_sl'] = df.trailing_sl.shift().sub(df['difference']).fillna(df['trailing_sl'])
Upvotes: 2