Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling averages on groups

Tags:

python

pandas

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?

like image 839
cjm2671 Avatar asked Dec 10 '25 23:12

cjm2671


1 Answers

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

s.groupby(level=0).rolling(10).mean()
like image 89
piRSquared Avatar answered Dec 13 '25 12:12

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!