rolling
df["col"].rolling(window=3).mean() computes the average of each value and the two before it, giving NaN for the first rows until the window is full. Any aggregation works (sum, std, max) and window can be a time offset such as "7D" on a datetime index.
Syntax
Series.rolling(window, min_periods=None, center=False).agg_method()| Part | What it is |
|---|---|
window | Number of rows, or an offset string like "7D" for a datetime index |
min_periods | Minimum rows needed to produce a value (default equals window) |
center | True places the window label in its middle |
Examples
import pandas as pd
df = pd.DataFrame({"day": range(1, 7), "sales": [10, 20, 30, 40, 50, 60]})
df["ma3"] = df["sales"].rolling(3).mean()
dfResult: day sales ma3 0 1 10 NaN 1 2 20 NaN 2 3 30 20.0 3 4 40 30.0 4 5 50 40.0 5 6 60 50.0
df["sales"].rolling(3, min_periods=1).mean().tolist()Result: [10.0, 15.0, 20.0, 30.0, 40.0, 50.0]
min_periods=1 averages whatever is available in the first rows.
df["sales"].rolling(2).sum().tolist()Result: [nan, 30.0, 50.0, 70.0, 90.0, 110.0]
Common mistakes
- Leading NaN values: expected until window rows exist; set min_periods=1 if you want partial averages.
- ValueError: window must be an integer 0 or greater: an offset like "7D" requires a sorted DatetimeIndex (or on="date_col").
- Rolling across group boundaries mixes customers: use df.groupby("id")["v"].rolling(3).mean() or transform.
Practice rolling
These drills check your answer on live data, free, no account needed.
- Rolling averageReturn the 3-day rolling average of `visits`. The first two days do not have three values yet, so they should be NaN.
Questions
How do I compute an exponential moving average?
df["col"].ewm(span=10).mean() weights recent values more, with no leading NaN.
How do I do a rolling average per group?
df["ma"] = df.groupby("id")["v"].transform(lambda s: s.rolling(3, min_periods=1).mean()) keeps the result aligned with the original rows.
What is expanding?
df["col"].expanding().mean() uses all rows from the start up to the current one, a cumulative average.
Related
- shift and diffHow to use shift and diff in pandas to get the previous or next row, compute the change and percent change between periods, and lag within groups.
- cumsumHow to compute a running total in pandas with cumsum, cumulative sums per group with groupby, cumulative max and count, cumulative percentages, and resets.
- resampleHow to resample a time series in pandas: monthly, weekly or daily buckets with sum or mean, upsample with ffill, use a date column with on, and new aliases.
- transformHow groupby transform works in pandas: broadcast a group sum or mean to each row, share of group total, group-wise normalization, and transform versus agg.