Sub topic 1
What a window calculation is
Prerequisites
This chapter assumes you can:
- Read basic Python and run short scripts.
- Create a pandas
SeriesorDataFrameand select columns and rows from it. - Compute simple statistics such as mean, sum and standard deviation.
- Use
groupbyfor a per-group aggregation. - Build a
DatetimeIndex. You only need it for later chapters, but it helps to know it exists.
The code uses pandas imported as pd. The examples work on pandas 1.x and 2.x unless noted.
The problem windows solve
A plain aggregation collapses a whole column into one number. s.mean() answers the question "what is the average of everything?" That is often too coarse. Suppose you track daily sales. A single average hides trends. You usually want "the average of the last 7 days, as of each day", which gives you a new value for every day.
A window calculation computes a statistic over a subset of rows near each row, and does it again for every row. The subset is the window. As you move from row to row, the window moves with you. In pandas the rows in the window are chosen by position or by time, relative to the current row.
Two properties define the idea:
- Each output value is computed from a window of input rows, not from the whole column.
- The output has one value per input row. It keeps the input's length and index.
Window, aggregation and groupby compared
The three operations are easy to confuse because all of them use mean, sum and similar functions. The difference is in which rows feed each result and how many results come out.
Here is one small dataset used with all three:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"sales": [10, 20, 30, 50],
})
print(df["sales"].mean()) # 27.5
print(df.groupby("store")["sales"].mean()) # A 15.0, B 40.0
print(df["sales"].rolling(2).mean()) # NaN, 15.0, 25.0, 40.0The three results look like this:
| Operation | Rows used for each result | Results returned | Output for the data above |
|---|---|---|---|
| `df["sales"].mean()` | All rows | One number | 27.5 |
| `groupby("store")["sales"].mean()` | All rows with the same key | One per group | 15.0 and 40.0 |
| `df["sales"].rolling(2).mean()` | The current row and the one before it | One per input row | NaN, 15.0, 25.0, 40.0 |
Notice the third result. It has four values for four rows. The value at row 2 is 25.0, the mean of 20 and 30. Those two rows belong to different stores, so a plain rolling window ignores group boundaries. Chapter 8 of this tutorial shows how to combine groupby with windows when you want to respect them.
A groupby partitions the data into separate pieces that do not overlap. Windows overlap. Row 2 appears in the window for row 2 and in the window for row 3.
The window families in pandas
pandas provides three window types. Each has a method on Series and DataFrame.
| Method | Window at row `t` | Typical use |
|---|---|---|
| `rolling(...)` | A fixed number of rows ending at `t`, or a fixed time span ending at `t` | Moving average, rolling standard deviation |
| `expanding(...)` | Everything from the first row through `t` | Running mean, running maximum |
| `ewm(...)` | All rows up to `t`, weighted so that recent rows count more | Smoothing that reacts quickly to new data |
This chapter introduces the shared model. Later chapters cover each family and its options in detail.
The anatomy of a rolling call
A rolling calculation has two steps, and the code reflects them:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
window = s.rolling(window=3) # step 1: describe the window
result = window.mean() # step 2: choose the statistic
print(result)
# 0 NaN
# 1 NaN
# 2 2.0
# 3 3.0
# 4 4.0
# 5 5.0
# dtype: float64Step 1 returns a Rolling object. It computes nothing. It only stores the settings: the window size and options such as min_periods, center and closed. Step 2 calls an aggregation method on that object, such as mean, sum, std, min or max. Only then does pandas do any arithmetic.
This split explains a common surprise. If you forget the aggregation and print s.rolling(3), you get a description of the object, not numbers. No error is raised, because creating the object is valid.
What each result means
Take the third value, 2.0 at index 2. The window of size 3 ending at index 2 contains the values 1, 2 and 3. Their mean is 2.0. At index 3 the window slides one row forward and contains 2, 3 and 4. The mean is 3.0.
By default, the window is trailing. It ends at the current row and looks backward. The current row is included. So a window of 3 means "this row and the two before it".
You can check the model by writing the same calculation by hand:
import numpy as np
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
manual = pd.Series(
[s.iloc[i - 2 : i + 1].mean() if i >= 2 else np.nan for i in range(len(s))]
)
print(manual.equals(s.rolling(3).mean())) # TrueThe loop slices three rows ending at row i and averages them. For the first two rows, a full window does not exist, so the loop produces NaN. This is exactly what rolling does, only vectorized and much faster.
Why the first values are NaN
By default, pandas returns a result only when the window is full. With window=3, rows 0 and 1 have fewer than three values behind them. Rather than report a statistic computed from an incomplete window, pandas returns NaN. In general, a window of size n produces n - 1 leading NaN values.
This is a default, not a rule. The min_periods option lowers the number of values required. Chapter 3 covers it. For now, remember that leading NaN values mean "not enough history yet". They do not signal an error in your data.
Output shape and index
A window calculation on a Series returns a Series with the same index. On a DataFrame it returns a DataFrame with the same index and columns. This makes it easy to attach the result to the original data:
import pandas as pd
df = pd.DataFrame({"sales": [10, 20, 30, 40, 50, 60]})
df["sales_avg3"] = df["sales"].rolling(3).mean()
print(df)
# sales sales_avg3
# 0 10 NaN
# 1 20 NaN
# 2 30 20.0
# 3 40 30.0
# 4 50 40.0
# 5 60 50.0Because the index is preserved, pandas aligns the result with the original rows without any merging. This index preservation is what separates a window calculation from a groupby aggregation. A groupby aggregation changes the index to the group keys.
Compare this with cumsum. The two are related. s.expanding().sum() and s.cumsum() give the same numbers, because an expanding window is a window that starts at the first row:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print((s.expanding().sum() == s.cumsum()).all()) # TrueThe window view is more general, because it applies to any statistic. There is no cumstd method, but s.expanding().std() works.
How the window slides
The diagram shows how one output value is produced for a window of size 3 at row 3.
The loop in the diagram runs once per row. Output is placed at the row where the window ends, which is why the result stays aligned with the input.
Windows measured in rows or in time
An integer window, such as rolling(3), counts rows. Every window holds the same number of rows, whatever the values in the index are.
A string window, such as rolling("3D"), measures time. It requires a datetime-like index. Each window covers a span of time, so the number of rows inside can differ from one window to the next:
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
df = pd.DataFrame({"sales": [10, 20, 30, 40]}, index=idx)
df["sales_3d"] = df["sales"].rolling("3D").sum()
print(df)
# sales sales_3d
# 2024-01-01 10 10.0
# 2024-01-02 20 30.0
# 2024-01-04 30 50.0
# 2024-01-07 40 40.0On 2024-01-04 the window covers the interval after 2024-01-01 up to and including 2024-01-04. It contains the rows for January 2 and January 4, so the sum is 20 + 30 = 50. On 2024-01-07 only the row for that day falls inside the span. Time-based windows do not produce leading NaN values by default, because the minimum row count defaults to one. Chapter 6 covers them fully.
Choose by what your question means. "The last 5 readings" is a row window. "The last 5 days", when readings can be missing on some days, is a time window.
Common errors
These mistakes come up often when people first use windows:
- Printing the
Rollingobject. Without an aggregation method, no numbers appear. Add.mean()or another statistic. - Expecting fewer rows. The output always has the input's length. Rows with incomplete windows hold
NaN. They are not dropped. Usedropna()if you want to remove them. - Assuming the window excludes the current row. By default it includes it. If you need only earlier rows, you must shift the result. Chapter 9 explains why this matters for prediction tasks.
- Using an invalid window size. A window size of zero or a negative number raises a
ValueError. A float is accepted only in specific cases, so use an integer for row windows. - Ignoring unsorted data. A row window follows the physical row order. If your data is not sorted the way you intend, the window combines the wrong neighbors. Sort first with
sort_index()orsort_values(). Time-based windows require a monotonic index and raise an error otherwise. - Mixing groups. A rolling window on a DataFrame with several stores or sensors slides straight across group boundaries, as the
storeexample above showed. - Passing non-numeric columns. Rolling statistics such as
meanneed numeric data. Select the numeric columns first, for exampledf[["sales"]].
Choosing between the three tools
Use these questions to decide:
- Do you need one number for the whole column? Use a plain aggregation.
- Do you need one number per category? Use
groupby. - Do you need a value for every row that summarizes nearby rows? Use a window.
Within windows, choose the family by how the window should grow. Use rolling when you want a constant-size recent view. Use expanding when you want everything seen so far. Use ewm when you want everything seen so far, with older rows fading out.
Exercise
A DataFrame has 10 rows. You run df["x"].rolling(4).mean(). How many values in the result are NaN, which rows are they, and why does the result still have 10 values?
Show answer
Three values are NaN, at rows 0, 1 and 2, because a window of 4 needs four rows and the first full window ends at row 3. The result has 10 values because a window calculation returns one value per input row and keeps the original index. Rows with an incomplete window are filled with NaN, not dropped.
Exercise
Given s = pd.Series([2, 4, 6, 8]), what does s.rolling(2).mean() return, and how does it differ from s.mean() and from s.expanding().mean()?
Show answer
s.rolling(2).mean() returns NaN, 3.0, 5.0, 7.0, which are the means of each pair of adjacent rows, and the first value is NaN because the first window has only one row. s.mean() returns the single number 5.0 for the whole Series. s.expanding().mean() returns 2.0, 3.0, 4.0, 5.0, because each window starts at row 0 and grows. Only the last of these values equals s.mean().