Home > Software design >  Compute percentage changes with next row Pandas
Compute percentage changes with next row Pandas

Time:12-10

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

   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

CodePudding user response:

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

CodePudding user response:

You can do shift with pct_change

n = 2
df['new'] = df.close.pct_change(periods=n).shift(-n)
df
Out[247]: 
   close return_n       new
0    100    1.00%  0.000000
1    101   -0.99% -0.019802
2    100   -1.00% -0.050000
3     99   -4.04%  0.030303
4     95    7.37%       NaN
5    102      NaN       NaN
  • Related