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?
你想要groupby(level=0)
然后rolling(n).mean()
s.groupby(level=0).rolling(10).mean()
如果您希望滚动平均值是同一数据帧中的新列:
df['rolling_mean'] = df.groupby(level=0).rolling(window_size).mean().values
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.