Rolling & Expanding Windows

Python · GroupBy & SQL-Style Analytics

Theory

s.rolling(window=3).mean() computes a moving average: each row gets the mean of itself and the two rows before it. The first two rows have fewer than 3 values and return NaN unless you set min_periods=1. Any aggregation works on the window - sum(), max(), min(), std(), median(). center=True centres the window on the row. For time series with a DatetimeIndex, rolling('7D') uses a time window (the last 7 days) instead of a fixed number of rows.

expanding() is a window that starts at the first row and grows: s.expanding().mean() is the average of everything so far. Per-group windows need care so they do not cross groups: df.groupby('city')['amount'].transform(lambda s: s.rolling(2, min_periods=1).mean()) keeps the original row order and index. In SQL this is AVG(amount) OVER (PARTITION BY city ORDER BY day ROWS BETWEEN 1 PRECEDING AND CURRENT ROW).

Why we use it

Daily numbers are noisy. Moving averages smooth them to show the trend, rolling sums give 'last 7 days' totals, and expanding windows give running averages - all common in dashboards and forecasting.

When to use it

Use rolling for fixed-size or time-based trailing windows, expanding for 'since the start' statistics and cumsum for simple running totals. Sort by time first; group with transform when each entity needs its own window.

How it works

  1. Time-ordered numeric column
  2. Trailing window of fixed size? Yes: rolling(n) or rolling('7D'). No: expanding() from the start.
  3. For each row, collect the values in its window
  4. Enough values (min_periods)? Yes: Compute mean / sum / max. No: Return NaN.
  5. Smoothed or windowed column

Syntax

s.rolling(window=n, min_periods=1).mean()
s.rolling('7D').sum()          # needs a DatetimeIndex
s.expanding().mean()
df.groupby('key')['col'].transform(lambda s: s.rolling(n).mean())

Example

df['ma_3'] = df['amount'].rolling(3).mean()
df['avg_so_far'] = df['amount'].expanding().mean()

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic