df.rolling(): Manual
What is a rolling window in pandas and how is it used?
Answer
The df.rolling() function is a function (method really) of the DataFrame object which allows us to compute statistics over a moving window of fixed size and fixed step.
A rolling window call returns a Rolling object, not a Series or DataFrame. It becomes a Series or DataFrame only after we apply a function such as mean(), sum(), or apply().
The main parameters are:
window: the size of the rolling windowmin_periods: minimum number of non-NA observations required to produce a value/statisticclosed: which side of the interval is closed (valid strings:"left","right","both","neither")step/size: the step size with which we roll the window
# Example: rolling mean of a temperature column
rolling_mean = (
df["temperature"]
.rolling(window=24, min_periods=12, step=2)
.mean().dropna()
)Notes and comments
Comment 1: This multi-line syntax with parentheses is commonly used to improve readability when chaining many functions.