Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compute percentage changes with next row Pandas

I want to compute the percentage change with the next n row. I’ve tried pct_change() but I don’t get the expected results

For example, with n=1

   close return_n
0    100    1.00%
1    101   -0.99%
2    100   -1.00%
3     99   -4.04%
4     95    7.37%
5    102    NaN

With n=2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   close return_n
0    100    0.00%
1    101   -1.98%
2    100   -5.00%
3     99    3.03%
4     95      NaN
5    102      NaN

>Solution :

Use pct_change and shift:

N = 2
df['return_n'] = df['close'].pct_change(N).mul(100).round(2).shift(-N)
print(df)

# Output:
   close  return_n
0    100      0.00
1    101     -1.98
2    100     -5.00
3     99      3.03
4     95       NaN
5    102       NaN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading