Home > Net >  How to apply formula to a dataframe in pandas
How to apply formula to a dataframe in pandas

Time:10-17

       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

CodePudding user response:

for x in range(len(df)-1): df['Atr'][x 1:] = (df['Atr'][x]*(14-1) df['tr'][x 1])/14

I hope this helps. I used a for loop and offset the cell being assigned by one.

CodePudding user response:

apply doesn't you here you are doing recursive calculation. The value of the next row depends on the value of the current row, which you must calculate.

A simple for loop will do the job:

tr, atr = df[["tr", "Atr"]].to_numpy().T
for i in range(1, len(atr)):
    atr[i] = (atr[i-1] * 13   tr[i]) / 14

df["Atr"] = atr

It's clean, readable and have the same form as your formula. The performance isn't the fastest but if this is too slow for you, look at numba to JIT-compile the snippet.

CodePudding user response:

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
  • Related