close

How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?

  1. How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?

    MaxU solutions suits in your case. If you want to perform more complex computations based on your previous rows you should use shift

  2. subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop

    MaxU solutions suits in your case. If you want to perform more complex computations based on your previous rows you should use shift

Method 1

you can use pct_change() or/and diff() methods

Demo:

In [138]: df.Close.pct_change() * 100
Out[138]:
0         NaN
1    0.469484
2    0.467290
3   -0.930233
4    0.469484
5    0.467290
6    0.000000
7   -3.255814
8   -3.365385
9   -0.497512
Name: Close, dtype: float64

In [139]: df.Close.diff()
Out[139]:
0      NaN
1    0.125
2    0.125
3   -0.250
4    0.125
5    0.125
6    0.000
7   -0.875
8   -0.875
9   -0.125
Name: Close, dtype: float64

Method 2

MaxU solutions suits in your case. If you want to perform more complex computations based on your previous rows you should use shift

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read