gpt4 book ai didi

python - Dataframe 的降序过滤

转载 作者:太空宇宙 更新时间:2023-11-03 21:42:44 24 4
gpt4 key购买 nike

我有一个数据框,例如

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

我尝试过实现一个计数器,但没有那么幸运。提前致谢。

最佳答案

您可以使用带有几个 bool 标志的手动循环。这里我使用 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

关于python - Dataframe 的降序过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com