I would like to compute the 1 year rolling average for each line on the Dataframe below
test:
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
...
For example, I would need to calculate:
I tried:
test.groupby(['id','date'])['variation'].rolling(window=1,freq='Y',on='date').mean()
but I got the error message:
ValueError: invalid on specified as date, must be a column (if DataFrame) or None
How can I use the pandas rolling() function is this case?
[EDIT 1]
Thank you Sacul
I tested:
df['date'] = pd.to_datetime(df['date'])
df.set_index('date').groupby('id').rolling(window=1, freq='Y').mean()['variation']
But freq='Y' doesn't work (I got: ValueError: Invalid frequency: Y) Then I used window = 365, freq = 'D'.
But there is another issue: because there is never 365 consecutive dates for each couple id-date, the result is always empty. Even if there missing dates, I would like to ignore them and consider all dates between the current date and the current date - 365 to compute the rolling mean. for instance, imagine I have:
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
Then,
- for 7034 2018-03-14: I would like to compute MEAN(4.139148e-06,4.953194e-07, 2.854749e-06)
- for 7034 2018-03-13: I would like to compute also MEAN(4.139148e-06,4.953194e-07, 2.854749e-06)
How can I do that?
[EDIT 2]
Finaly I used the formula below to calculate rolling median, averages and standard deviation on 1 Year by ignoring missing values:
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)