我希望计算这个数据框 test
中每一行的1年滚动平均值:
index id date variation
2313 7034 2018-03-14 4.139148e-06
2314 7034 2018-03-13 4.953194e-07
2315 7034 2018-03-12 2.854749e-06
2316 7034 2018-03-09 3.907458e-06
2317 7034 2018-03-08 1.662412e-06
2318 7034 2018-03-07 1.346433e-06
2319 7034 2018-03-06 8.731700e-06
2320 7034 2018-03-05 7.145597e-06
2321 7034 2018-03-02 4.893283e-06
...
例如,我需要计算:
7034
的变化平均值7034
的变化平均值我尝试过:
test.groupby(['id','date'])['variation'].rolling(window=1,freq='Y',on='date').mean()
但我收到了错误信息:
ValueError: invalid on specified as date, must be a column (if DataFrame) or None
在这种情况下,我该如何使用 pandas 的 rolling()
函数?
[编辑 1] [感谢 Sacul]
我已经进行了测试:
df['date'] = pd.to_datetime(df['date'])
df.set_index('date').groupby('id').rolling(window=1, freq='Y').mean()['variation']
但是freq='Y'
无法正常工作(我得到了:ValueError:Invalid frequency: Y
)。然后我使用了window = 365,freq ='D'
。
但是还有一个问题:因为每个组合的id-date
从未连续出现365个日期,所以结果总是为空。即使存在缺失的日期,我也希望忽略它们并考虑当前日期和(当前日期-365)之间的所有日期来计算滚动均值。例如,假设我有:
index id date variation
2313 7034 2018-03-14 4.139148e-06
2314 7034 2018-03-13 4.953194e-07
2315 7034 2017-03-13 2.854749e-06
那么,
- 对于7034 2018-03-14:我想计算MEAN(4.139148e-06,4.953194e-07, 2.854749e-06)
- 对于7034 2018-03-13:我也想计算MEAN(4.139148e-06,4.953194e-07, 2.854749e-06)
我该怎么做?
[EDIT 2]
最后,我使用以下公式来计算1年内的滚动中位数、平均值和标准差,并忽略缺失值:
pd.rolling_median(df.set_index('date').groupby('id')['variation'],window=365, freq='D',min_periods=1)
pd.rolling_mean(df.set_index('date').groupby('id')['variation'],window=365, freq='D',min_periods=1)
pd.rolling_std(df.set_index('date').groupby('id')['variation'],window=365, freq='D',min_periods=1)