Rolling mean with customized window with Pandas

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)

For more current version of Pandas (please see 0.23.4 documentation https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html), you don't have rolling_mean anymore. Instead, you will use

DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None)

For your example, it will be:

df.rolling(5,center=True).mean()

Tags:

Python

Pandas