🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

df.rolling()

AI & DATA SCIENCE // df-rolling

df.rolling(window) creates a rolling (sliding) window view over the data, letting you compute a moving statistic, like a moving average, over each window of consecutive rows.

Syntax

df.rolling(window).agg_method()

Deep Dive Course

rolling(window) groups each row together with the (window - 1) rows immediately before it, and like groupby()/resample(), it returns a lazy Rolling object that only produces results once you chain an aggregation, most commonly .mean() for a moving average, but also .sum(), .std(), .min()/.max(), and others. The first (window - 1) rows don't have enough preceding data to fill a complete window, so they produce NaN by default, unless min_periods is set to a smaller value that allows a partial window to still produce a result.

1Understanding df.rolling()

rolling(window) groups each row together with the (window - 1) rows immediately before it, and like groupby()/resample(), it returns a lazy Rolling object that only produces results once you chain an aggregation, most commonly .mean() for a moving average, but also .sum(), .std(), .min()/.max(), and others. The first (window - 1) rows don't have enough preceding data to fill a complete window, so they produce NaN by default, unless min_periods is set to a smaller value that allows a partial window to still produce a result.

💡

The first (window - 1) rows of a rolling calculation are NaN by default, since there isn't yet enough preceding data to fill a full window — pass min_periods to allow the calculation to still produce a result from a partial window if that's acceptable for your use case.

editor.html
import pandas as pd

df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3).mean())
localhost:3000

2Practical Example

Here is a real-world application of df.rolling() showing how it is used in production Pandas code.

editor.html
import pandas as pd

df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3, min_periods=1).mean())
localhost:3000

3Best Practices

Follow these guidelines when working with df.rolling():

1. Choose the window size deliberately based on the actual time period you want to smooth over, like 7 for a weekly moving average on daily data, not an arbitrary number

2. Set min_periods explicitly if you want partial windows at the start of the data to still produce a result, rather than NaN

3. Combine rolling().mean() with the original series in a plot to visually compare raw, noisy data against its smoothed trend

⚠️

Tip: The first (window - 1) rows of a rolling calculation are NaN by default, since there isn't yet enough preceding data to fill a full window — pass min_periods to allow the calculation to still produce a result from a partial window if that's acceptable for your use case.

editor.html
import pandas as pd

df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3).mean())
localhost:3000

Examples

Example 01Basic Usage
import pandas as pd

df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3).mean())
Example 02Advanced Example
import pandas as pd

df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3, min_periods=1).mean())

Best Practices

  • Choose the window size deliberately based on the actual time period you want to smooth over, like 7 for a weekly moving average on daily data, not an arbitrary number
  • Set min_periods explicitly if you want partial windows at the start of the data to still produce a result, rather than NaN
  • Combine rolling().mean() with the original series in a plot to visually compare raw, noisy data against its smoothed trend

Interview Question

Why do the first two values of a 3-row rolling mean come out as NaN by default?

Hint: Think about how many preceding rows exist for row 0 and row 1 specifically.

A rolling window of size 3 needs 3 consecutive values to compute its mean — for row 0, there are zero preceding rows available, and for row 1, there's only one preceding row, so neither has enough data to fill a complete window of 3. By default, rolling() requires a full window before it will produce a result, so it fills those positions with NaN rather than computing a mean from an incomplete set of values. Passing min_periods=1 explicitly allows it to compute a result from however many values are actually available, even if that's fewer than the full window size, which is why min_periods=1 fills in those otherwise-NaN starting positions instead.

Exercises

MediumPractice using df.rolling() in a real scenario.
View Solution
import pandas as pd

df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3).mean())

Frequently Asked Questions

Why do the first two values of a 3-row rolling mean come out as NaN by default?

A rolling window of size 3 needs 3 consecutive values to compute its mean — for row 0, there are zero preceding rows available, and for row 1, there's only one preceding row, so neither has enough data to fill a complete window of 3. By default, rolling() requires a full window before it will produce a result, so it fills those positions with NaN rather than computing a mean from an incomplete set of values. Passing min_periods=1 explicitly allows it to compute a result from however many values are actually available, even if that's fewer than the full window size, which is why min_periods=1 fills in those otherwise-NaN starting positions instead.

Related Functions

df-shiftdf-resamplenp-mean