Descending Filtering For Dataframe
I have a dataframe such as Index Results Price 0 Buy 10 1 Sell 11 2 Buy 12 3 Neutral 13 4 Buy 14 5 Sell 15 I would l
Solution 1:
You can use a manual loop with a couple of Boolean flags. Here I use numba
to add some element of optimisation:
from numba import njit
@njit
def get_diffs(results, prices):
res = np.full(prices.shape, np.nan)
prev_one, prev_zero = True, False
for i in range(len(results)):
if prev_one and (results[i] == 0):
price_start = prices[i]
prev_zero, prev_one = True, False
elif prev_zero and (results[i] == 1):
res[i] = prices[i] - price_start
prev_zero, prev_one = False, True
return res
results = df['Results'].map({'Buy': 0, 'Sell': 1})
df['Difference'] = get_diffs(results.values, df['Price'].values)
print(df)
Index Results Price Difference
0 0 Buy 10 NaN
1 1 Sell 11 1.0
2 2 Buy 12 NaN
3 3 Neutral 13 NaN
4 4 Buy 14 NaN
5 5 Sell 15 3.0
Post a Comment for "Descending Filtering For Dataframe"