数据帧的降序筛选



>我有一个数据帧,例如

Index   Results  Price
0       Buy      10
1       Sell     11
2       Buy      12
3       Neutral  13
4       Buy      14
5       Sell     15

我想最终以降序方式返回买入和卖出结果的第一个连续组合的价格差异。使得第一输出相差1,第二输出相差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

我试图实现一个计数器,但没有这样的运气。提前谢谢。

您可以使用带有几个布尔标志的手动循环。在这里,我使用numba添加一些优化元素:

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

最新更新