gpt4 book ai didi

python - 使用 pandas 计算下一行的值作为前一行的函数

转载 作者:行者123 更新时间:2023-11-30 22:15:33 36 4
gpt4 key购买 nike

我正在尝试为我的 DataFrame 实现以下算法:

if Tenure==0: 
s=1
else:
s = (previous value from "s") * (1-previous value from "h")

s作为h的函数进行计算,初始值为1。

输入数据框:

        popt    stopt    popcum    h        s
Tenure
0.0 2383 508.0 5067890 0.000100 1
1.0 18358 17310.0 5065507 0.003417 0
2.0 16742 15103.0 5047149 0.002992 0
3.0 13298 11361.0 5030407 0.002258 0
4.0 9566 9522.0 5017109 0.001898 0


result3["s"]=result3.apply(funkcyjka)

为了跳过第一个条件,我刚刚编辑了第一行,因为它是唯一一个 Tenure = 0 的行

这是我想到的:

def funkcyjka(res):
x=0
lol=(res["s"].iloc[x])*(1-(res["h"].iloc[x]))
x+=1
return lol

但它没有达到我的预期。我如何在我的数据框中实现这个功能?

最佳答案

如果您在纸上追踪这一点,这就是每行 s 的实际计算结果:

1
1 * (1 - h0)
(1 - h0) * (1 - h1)
(1 - h0) * (1 - h1) * (1 - h2)
...

因此,您需要在这里使用 shift + cumprod:

df['s'] = (1 - df['h'].shift()).fillna(1).cumprod()
df
popt stopt popcum h s
Tenure
0.0 2383 508.0 5067890 0.000100 1.000000
1.0 18358 17310.0 5065507 0.003417 0.999900
2.0 16742 15103.0 5047149 0.002992 0.996483
3.0 13298 11361.0 5030407 0.002258 0.993502
4.0 9566 9522.0 5017109 0.001898 0.991259

关于python - 使用 pandas 计算下一行的值作为前一行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50265415/

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