0

OK, need some help here! I have the following dataframe.

df2 = {'Value': [123, 126, 120, 121, 123, 126, 120, 121, 123, 126],
       'Look-back': [2, 3, 4, 5, 3, 6, 2, 4, 2, 1]}

df2 = pd.DataFrame(df2)

df2

I'd like to add a third row that shows the simple moving average of the 'Value' column with the rolling look-back period of the 'Look-back' column. My thought was to do this.

df2['Average'] = df2['Value'].rolling(df['Look-back']).mean()

Of course this doesn't work because the rolling() function needs an integer key value and I'm supplying a series.

How do I get what I'm after here?

Stephen Ostermiller
  • 21,408
  • 12
  • 81
  • 104
km84
  • 11
  • 2
  • 1
    What you are asking for can be described as a dynamic moving average. There is an existing answer [here](https://stackoverflow.com/a/59920226/9987623) for computing a dynamic moving sum. If you just change the method to `'mean'` and update the window on the function's `return` line as needed (it currently includes the current row in calculations (with `+1`) plus the number of previous rows defined by lookback value), you should get what you need. – AlexK May 27 '22 at 21:58

0 Answers0