3

I've got a Series of the form:

Contract  Date      
196012    1960-01-05    110.70
          1960-01-07    110.70
          1960-01-08    110.40
          1960-01-11    110.00
          1960-01-12    109.60
          1960-01-13    109.70
          1960-01-14    109.50
          1960-01-15    109.60
          1960-01-18    109.60
          1960-01-19    110.20
          1960-01-20    110.00
          1960-01-21    110.30
          1960-01-22    110.00
          1960-01-25    109.50
          1960-01-26    109.60
          1960-01-28    109.70
          1960-01-29    110.00
          1960-02-01    109.60
          1960-02-02    109.60
          1960-02-03    109.60
          1960-02-04    110.10
          1960-02-05    110.20
          1960-02-08    110.20
          1960-02-09    110.50
          1960-02-10    110.10
          1960-02-11    109.50
          1960-02-12    110.40
          1960-02-15    110.00
          1960-02-16    109.50
          1960-02-17    110.00
                         ...  
201812    2016-06-29    403.00
          2016-06-30    398.00
          2016-07-01    404.25
          2016-07-05    402.00
          2016-07-06    394.00
201912    2015-12-16    417.00
          2015-12-17    415.00
          2015-12-23    416.00

Where the index is a hierarchical multi-index. I'd like to apply a rolling window average to each contract, and save the results to a new column.

What's the right way?

cjm2671
  • 18,348
  • 31
  • 102
  • 161

2 Answers2

2

You want to groupby(level=0) then rolling(n).mean()

s.groupby(level=0).rolling(10).mean()
piRSquared
  • 285,575
  • 57
  • 475
  • 624
1

If you want the rolling mean to be a new column in the same dataframe:

df['rolling_mean'] = df.groupby(level=0).rolling(window_size).mean().values

Grr
  • 15,553
  • 7
  • 65
  • 85