Calculate the usual moving average using the direct (or reverse) window, and then use the shift method to re-center, as you wish.
data_mean = pd.rolling_mean(data, window=5).shift(-2)
If you want to average more than two data points before and after observation (a total of 5 data points), do window=5 .
For instance,
import pandas as pd data = pd.Series(range(1, 9)) data_mean = pd.rolling_mean(data, window=5).shift(-2) print(data_mean)
gives
0 NaN 1 NaN 2 3 3 4 4 5 5 6 6 NaN 7 NaN dtype: float64
As kadee points out , if you want to center the moving average, use
pd.rolling_mean(data, window=5, center=True)
source share