Rolling mean with customized window with Pandas
pandas, python
Solution
Compute the usual rolling mean with a forward (or backward) window and then use the `shift` method to re-center it as you wish.
data_mean = pd.rolling_mean(data, window=5).shift(-2)
If you want to average over 2 datapoints before and after the observation (for a total of 5 datapoints) then make the `window=5`.
For example,
import pandas as pd
data = pd.Series(range(1, 9))
data_mean = pd.rolling_mean(data, window=5).shift(-2)
print(data_mean)
yields
0 NaN
1 NaN
2 3
3 4
4 5
5 6
6 NaN
7 NaN
dtype: float64
As kadee points out, if you wish to center the rolling mean, then use
pd.rolling_mean(data, window=5, center=True)
Problem
Is there a way to customize the window of the rolling_mean function? ``` data 1 2 3 4 5 6 7 8 ``` Let's say the window is set to 2, that is to calculate the average of 2 datapoints before and after the obervation including the observation. Say the 3rd observation. In this case, we will have `(1+2+3+4+5)/5 = 3`. So on and so forth.