TExcelTAD
Home › pandas › Window Functions (rolling)

Window Functions (rolling)

A window function computes a statistic over a sliding group of neighbouring rows: the average of the last 7 days, the maximum of the last 3 readings. Moving averages smooth out noise so you can see the trend, and they're everywhere in finance, monitoring and sports analytics.

pandas has three kinds of windows:

Method Window
rolling(n) the last n rows (or a time span like "7D")
expanding() all rows from the start up to the current one
ewm(span=n) all rows, with exponentially decreasing weights for older ones

rolling()

python · try it yourself
import pandas as pd

steps = pd.Series([4200, 9800, 6100, 12500, 3000, 8800, 10400, 7600],
                  index=pd.date_range("2024-05-06", periods=8, freq="D"), name="steps")
print(pd.DataFrame({
    "steps": steps,
    "avg_3d": steps.rolling(3).mean().round(0),
    "max_3d": steps.rolling(3).max(),
}))
            steps  avg_3d   max_3d
2024-05-06   4200     NaN      NaN
2024-05-07   9800     NaN      NaN
2024-05-08   6100  6700.0   9800.0
2024-05-09  12500  9467.0  12500.0
2024-05-10   3000  7200.0  12500.0
2024-05-11   8800  8100.0  12500.0
2024-05-12  10400  7400.0  10400.0
2024-05-13   7600  8933.0  10400.0

Each avg_3d value is the mean of that day and the two before it. The first two rows are NaN because a full 3-row window isn't available yet.

min_periods and center

min_periods lets a window produce a result with fewer rows than its size. center=True places the window around the current row instead of ending at it:

python · try it yourself
import pandas as pd

s = pd.Series([1.0, 3.0, 5.0, 7.0, 9.0])
print(pd.DataFrame({
    "value": s,
    "trailing": s.rolling(3).mean(),
    "min_periods=1": s.rolling(3, min_periods=1).mean(),
    "centered": s.rolling(3, center=True).mean(),
}))
   value  trailing  min_periods=1  centered
0    1.0       NaN            1.0       NaN
1    3.0       NaN            2.0       3.0
2    5.0       3.0            3.0       5.0
3    7.0       5.0            5.0       7.0
4    9.0       7.0            7.0       NaN

Time-based windows

With a DatetimeIndex you can give the window as a duration. "3D" means "the last three calendar days", which handles gaps in the data correctly; a row count would not:

python · try it yourself
import pandas as pd

readings = pd.Series([20.0, 22.0, 30.0, 26.0, 24.0],
                     index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05",
                                           "2024-01-06", "2024-01-07"]))
print(pd.DataFrame({
    "value": readings,
    "last_3_rows": readings.rolling(3).mean(),
    "last_3_days": readings.rolling("3D").mean(),
}))
            value  last_3_rows  last_3_days
2024-01-01   20.0          NaN    20.000000
2024-01-02   22.0          NaN    21.000000
2024-01-05   30.0    24.000000    30.000000
2024-01-06   26.0    26.000000    28.000000
2024-01-07   24.0    26.666667    26.666667

On January 5th the 3-row window still reaches back to January 1st, whereas the 3-day window only includes the 3rd to the 5th, so it contains just the one reading.

A moving average chart

Smoothing makes a noisy series readable. Here are 90 days of made-up website visitors: a slow upward trend, a weekly rhythm and seeded random noise. The 7-day moving average removes the weekly ups and downs and reveals the trend:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
days = pd.date_range("2024-03-01", periods=90, freq="D")
trend = np.linspace(400, 600, 90)
weekly = 80 * np.sin(np.arange(90) / 7 * 2 * np.pi)
visitors = pd.Series(trend + weekly + rng.normal(0, 40, 90),
                     index=days, name="visitors")

ax = visitors.plot(alpha=0.4, label="daily", figsize=(8, 3.5))
visitors.rolling(7).mean().plot(ax=ax, linewidth=2.5, label="7-day average")
ax.legend()
ax.set_title("Website visitors")
plt.show()
print("Last 7-day average:", round(visitors.rolling(7).mean().iloc[-1], 1))
Last 7-day average: 592.9

expanding() and ewm()

expanding() grows from the first row: an expanding mean is the running average of everything so far, and an expanding max is the record to date. ewm() (exponentially weighted) gives recent values more influence, so it reacts faster to change than a simple moving average:

python · try it yourself
import pandas as pd

scores = pd.Series([70, 74, 69, 80, 85, 83, 90])
print(pd.DataFrame({
    "score": scores,
    "running_avg": scores.expanding().mean().round(2),
    "best_so_far": scores.expanding().max(),
    "ewm_span3": scores.ewm(span=3, adjust=False).mean().round(2),
}))
   score  running_avg  best_so_far  ewm_span3
0     70        70.00         70.0      70.00
1     74        72.00         74.0      72.00
2     69        71.00         74.0      70.50
3     80        73.25         80.0      75.25
4     85        75.60         85.0      80.12
5     83        76.83         85.0      81.56
6     90        78.71         90.0      85.78

Rolling per group

Combine groupby with rolling to compute windows separately for each group, here a 2-match average per team:

python · try it yourself
import pandas as pd

matches = pd.DataFrame({
    "team": ["A", "B", "A", "B", "A", "B"],
    "points": [3, 1, 0, 3, 3, 3],
})
matches["form"] = (matches.groupby("team")["points"]
                          .transform(lambda s: s.rolling(2, min_periods=1).mean()))
print(matches)
  team  points  form
0    A       3   3.0
1    B       1   1.0
2    A       0   1.5
3    B       3   2.0
4    A       3   1.5
5    B       3   3.0

Test yourself

With s.rolling(4).mean(), how many leading NaN values appear?

  1. 0
  2. 3
  3. 4
  4. 1

Which window grows to include every row from the start?

  1. rolling
  2. expanding
  3. ewm
  4. resample

Why use rolling("7D") instead of rolling(7) on daily data with missing days?

  1. It is faster
  2. It covers 7 calendar days regardless of how many rows exist
  3. rolling(7) is not allowed on dates
  4. There is no difference