3

I am calculating the time-based EWMA, as defined:

where:

On the following example data frame df:

index      time       x
0          1          5
1          1.3        4
2          1.4        8
3          2.8        3  

For example, at time 3:

I know that in python we can use df['ewma'] = df['x'].ewm(alpha = c) to calculate the simple ewma, but here c can only be a fixed float.

My question is: how do I handle changing parameter c? I could iterate through the entire df recursively to get the answers, but it seems really unsophisticated.

Any advice on how I could approach this problem? Thank you in advance!

LSF
  • 97
  • 6

1 Answers1

0

Use shift()

Essentially you need time[x] and time[x-1] to solve your problem, if I'm reading this right.

Simply create a new column:

df['time_prev'] = df['time'].shift(1)


print(df)

   index  time  x  time_prev
0      0   1.0  5        NaN
1      1   1.3  4        1.0
2      2   1.4  8        1.3
3      3   2.8  3        1.4

Then you can use time_prev for the previous value in your calculation. You can adjust it to older values by increasing .shift(3) as an example.

run-out
  • 3,114
  • 1
  • 9
  • 25
  • 1
    Thank you for your reply, you certainly read my need right, but the thing is df.ewm(alpha = c), here c can only be a float, not a series. So I cannot pass a series into the function if that makes sense. – LSF May 04 '19 at 20:16
  • 1
    Have you seen this [answer](https://stackoverflow.com/questions/42869495/numpy-version-of-exponential-weighted-moving-average-equivalent-to-pandas-ewm/42905202)? I don't think I can add anything to that. – run-out May 04 '19 at 21:53