本文介绍了数据框降序过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,例如
Index Results Price
0 Buy 10
1 Sell 11
2 Buy 12
3 Neutral 13
4 Buy 14
5 Sell 15
我想最终以降序返回买入"和卖出"结果的第一个连续组合的价格差.这样第一个输出的差为1,第二个输出的差为3.
I would like to ultimately return the price difference for the first continuous combination of Buy and then Sell Results in a descending manner. Such that the first output is a difference of 1, second output 3.
for buy in df:
if buy:
df['Buy Price'] = df['Price']
for sell in df:
if sell:
df['Sell Price'] = df['Price']
df['Difference'] = df['Sell Price'] - df['Buy Price']
所需的输出
Index Results Price Difference
0 Buy 10
1 Sell 11 1
2 Buy 12
3 Neutral 13
4 Buy 14
5 Sell 15 3
我试图实现一个计数器,但是没有运气.预先感谢.
I have attempted to implement a counter but with no such luck. Thanks in advance.
推荐答案
您可以使用带有两个布尔标志的手动循环.在这里,我使用numba
添加一些优化元素:
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
这篇关于数据框降序过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!