将下一行的值作为前一行的函数,并使用

2024-10-01 09:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的数据帧实现以下算法:

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)

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

我想到的是:

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

但它并没有达到我的期望。如何将此函数实现到数据帧?你知道吗


Tags: 数据函数from算法ifvaluereselse
1条回答
网友
1楼 · 发布于 2024-10-01 09:32:33

如果你把它写在纸上,这就是为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

相关问题 更多 >