我很难在以下包含重复索引的数据框中使用 pd.rolling_mean 函数:
amount
20140101 3
20140102 4
20140103 3
20140103 5
20140103 1
20140104 5
20140105 6
20140106 2
…
我需要计算“金额”的 3 天平均值,例如,从 20140101 到 20140103 的平均值应该是 (3+4+3+ 5+1)/5=3.2,从20140104到20140106的平均金额应该是(5+6+2)/3=4.3
有人知道怎么做吗?提前致谢!
请您参考如下方法:
你可以这样做:
>>> df
amount
20140101 3
20140102 4
20140103 3
20140103 5
20140103 1
20140104 5
20140105 6
20140106 2
>>> xf = df.groupby(level=0)['amount'].agg(['sum', 'count'])
>>> xf
sum count
20140101 3 1
20140102 4 1
20140103 9 3
20140104 5 1
20140105 6 1
20140106 2 1
>>> pd.rolling_sum(xf['sum'], 3, 0) / pd.rolling_sum(xf['count'], 3, 0)
20140101 3.000
20140102 3.500
20140103 3.200
20140104 3.600
20140105 4.000
20140106 4.333
dtype: float64
20140103 和 20140106 分别得到 3.2 和 4.3。
