0
       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

Praisi
  • 39
  • 5
  • Is `shift()` above a bitwise shift or list index shift? Please provide expected output. – Azhar Khan Oct 16 '22 at 13:29
  • i meant to write is previous Atr @AzharKhan – Praisi Oct 16 '22 at 14:04
  • Maybe this? https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html You could try to google pandas apply or something. – Barzi2001 Oct 16 '22 at 14:14
  • Does this answer your question? [How can I use the apply() function for a single column?](https://stackoverflow.com/questions/34962104/how-can-i-use-the-apply-function-for-a-single-column) – RMS Oct 16 '22 at 14:16
  • I believe you can implement your function using the apply method of pandas dataframe, as in here: https://stackoverflow.com/questions/34962104/how-can-i-use-the-apply-function-for-a-single-column. If you want to update values iteratively so that the formula in each row uses information from the previous row, you can have a look here: https://stackoverflow.com/questions/74074012/pandas-have-row-value-based-on-condition-that-is-related-to-previous-rows-value/74075824?noredirect=1#comment130794360_74075824 – RMS Oct 16 '22 at 14:20

3 Answers3

0

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.

Tyler Sims
  • 24
  • 2
0

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.

Code Different
  • 90,614
  • 16
  • 144
  • 163
0

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
SomeDude
  • 13,876
  • 5
  • 21
  • 44