[英]Rolling averages on groups
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.