Thursday, November 3, 2022

[FIXED] How to apply formula to a dataframe in pandas

Issue

       tr   Atr
0   0.00276 0.00276
1   0.01455 NaN
2   0.00895 NaN
3   0.00816 NaN
4   0.00596 NaN
5   0.00816 NaN
6   0.00844 NaN
7   0.01150 NaN
8   0.00473 NaN
9   0.00502 NaN

Please how to do a apply this formula to each tr

Atr = (prev_Atr * (14 - 1) + tr) / 14

what i want to do is

df["Atr"] = lambda x, y: (x * (14 -1) + y)/14

but i dont know how to assign

x = prev_Atr & y = tr


Solution

It seems you are looking for a rolling computation. But its not a simple sum() or such. You can achieve what you want with a simple for loop:

for i in df.index[1:]:
    df['Atr'].iloc[i] = (df['Atr'].iloc[i-1]*13 + df['tr'].iloc[i])/14

print(df):

        tr       Atr
0  0.00276  0.002760
1  0.01455  0.003602
2  0.00895  0.003984
3  0.00816  0.004282
4  0.00596  0.004402
5  0.00816  0.004671
6  0.00844  0.004940
7  0.01150  0.005408
8  0.00473  0.005360
9  0.00502  0.005336


Answered By - SomeDude
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.