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.
import pandas as pd
df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3).mean())2Practical Example
Here is a real-world application of df.rolling() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3, min_periods=1).mean())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.
import pandas as pd
df = pd.DataFrame({"price": [10, 12, 11, 15, 14, 18]})
print(df["price"].rolling(window=3).mean())