rolling() (Pandas)

s.rolling(window) creates a sliding window over a Series or DataFrame so you can compute moving statistics like rolling means and sums. It is the core tool for smoothing and trend analysis on ordered data.

Pandas

rolling(3).mean() computes the average of every 3 consecutive values, sliding the window forward one step at a time. The first window-1 results are NaN because there aren't yet enough points to fill the window. It is most often used on time series to smooth noise or build moving averages.

Like groupby, rolling is lazy: rolling(window) returns a Rolling object and does nothing until you chain an aggregation such as .mean(), .sum(), .std(), or .apply(). min_periods lets you produce a result before the window is full, and center=True aligns the window on the middle point instead of the right edge.

Its relatives are expanding (an ever-growing window from the start) and ewm (exponentially weighted, giving recent points more influence).

Syntax

s.rolling(window, min_periods=None, center=False).mean()

Examples

Python

import pandas as pd
s = pd.Series([1, 2, 3, 4])
print(s.rolling(2).sum())

Output:

0    NaN
1    3.0
2    5.0
3    7.0
dtype: float64

Learn it in a lesson

See also

Back to the Dictionary