Home > Back-end >  Pandas pct_change with moving average
Pandas pct_change with moving average

Time:06-22

I would like to use pandas' pct_change to compute the rate of change between each value and the previous rolling average (before that value). Here is what I mean:

If I have:

import pandas as pd

df = pd.DataFrame({'data': [1, 2, 3, 7]})

I would expect to get, for window size of 2:

0    NaN
1    NaN
2    1
3    1.8

, because roc(3, avg(1, 2)) = (3-1.5)/1.5 = 1 and same calculation goes for 1.8. using pct_change with periods parameter just skips previous nth entries, it doesn't do the job.

Any ideas on how to do this in an elegant pandas way for any window size?

CodePudding user response:

here is one way to do it, using rolling and shift

df['avg']=df.rolling(2).mean()
df['poc'] = (df['data'] - df['avg'].shift( 1))/ df['avg'].shift( 1)
df.drop(columns='avg')


    data    poc
0     1     NaN
1     2     NaN
2     3     1.0
3     7     1.8
  • Related