gpt4 book ai didi

python - 从 pandas 数据框(库存)计算数据的更有效方法

转载 作者:行者123 更新时间:2023-12-01 02:38:19 27 4
gpt4 key购买 nike

我想知道是否有更有效/更干净的方法来执行以下操作。假设我有一个包含 2 列的数据框,百分比(基于之前的价格)和操作,玩/买 (1) 或不玩/卖 (-1)。它基本上与股票有关。

为简单起见,请考虑示例 df:

Percent    Action
1.25 1
1.20 1
0.50 -1
0.75 1

我想生成以下内容。我只关心最终的金额,我只是展示这个表格供引用。假设我们一开始有 100 美元,并且处于不玩的状态。因此我们应该得到的金额为:

Playing    Percent    Action    Money
No 1.25 1 $100
Yes 1.20 1 $120
Yes 0.50 -1 $60
No 0.75 1 $60
Yes ... ... ...

第一行的金额没有变化,因为我们还没有玩。由于 Action 为 1,我们将播放下一个 Action 。百分比上升了 20%,因此我们得到了 120 美元。下一个 Action 仍然是 1,所以我们仍然会在下一个 Action 中。百分比下降到 50%,所以我们最终得到 60 美元。下一个 Action 是-1,因此我们不会玩。百分比下降到 75%,但由于我们没有玩,所以我们的钱保持不变。等等。

目前,我有以下代码。它工作正常,但只是想知道是否有更有效的方法使用 numpy/pandas 函数。我的基本上是遍历每一行并计算值。

playing = False
money = 10000

for index, row in df.iterrows():
## UPDATE MONEY IF PLAYING
if index > 0 and playing == True:
money = float(format(money*row['Percent'],'.2f'))

## BUY/SELL
if row['Action'] == 1:
if playing == False:
playing = True ## Buy, playing after this
elif row['Action'] == -1:
if playing == True:
playing = False ## Sell, not playing after this

最佳答案

你可以试试这个:

# decide whether to play based on action
df['Playing'] = df.Action.shift().eq(1)

# replace Percent for not playing row with 1 and then calculate the cumulative product
df['Money'] = '$' + df.Percent.where(df.Playing, 1).cumprod().mul(100).astype(str)

df
#Percent Action Playing Money
#0 1.25 1 False $100.0
#1 1.20 1 True $120.0
#2 0.50 -1 True $60.0
#3 0.75 1 False $60.0

关于python - 从 pandas 数据框(库存)计算数据的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45991998/

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