Sub topic 2
Choosing Window Aggregations in pandas
Assume you know how to create pandas Series and DataFrames, use a DatetimeIndex, calculate basic statistics, and group data with groupby. A window calculation applies an operation to a subset of nearby rows instead of to the entire object.
Choosing aggregations
After creating a rolling window, choose an aggregation such as mean, sum, or std:
import pandas as pd
sales = pd.Series([10, 20, 30, 40, 50])
result = sales.rolling(window=3).agg(["mean", "sum", "std"])
print(result)Each output row summarizes the current three-row window. The first two rows are NaN because three values are not available yet. Standard deviation also depends on its degrees-of-freedom setting, so inspect its behavior when you have very small windows.
You can call one aggregation directly:
rolling_sum = sales.rolling(3).sum()
rolling_mean = sales.rolling(3).mean()Window alignment with `center` and `closed`
By default, pandas places each result at the right edge of its window. With center=True, pandas places the result at the middle row:
centered = sales.rolling(3, center=True).mean()
print(centered)A centered window has missing values at both ends because the first and last rows cannot have a complete window on both sides.
For time-based windows, closed controls which boundary timestamps are included. The default is usually closed="right", representing (t - span, t]. Use closed="both" to include both endpoints.
Time-based windows on a `DatetimeIndex`
An integer window counts rows. A string window measures elapsed time. The index must contain timestamps and should be sorted.
import pandas as pd
dates = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04"])
df = pd.DataFrame({"sales": [10, 20, 30]}, index=dates)
df["sales_3d"] = df["sales"].rolling("3D", closed="right").sum()
print(df)The number of rows can differ between windows because the timestamps are irregular.
Expanding windows for running statistics
An expanding window always starts at the first row and grows:
running_mean = sales.expanding().mean()
running_max = sales.expanding().max()
print(running_mean)
print(running_max)Use rolling for recent history and expanding for all history accumulated so far.
Exercise
Which method computes a running mean that includes every earlier row?
Show answer
Use series.expanding().mean().