Sub topic 1
What a window calculation is
A window calculation computes a statistic for each row from a small set of nearby rows. This chapter explains how that differs from a plain aggregation or a groupby. It also introduces the two window types the rest of the tutorial builds on.
Prerequisites
This chapter assumes you can do the following:
- Write basic Python.
- Create and index pandas Series and DataFrames.
- Work with a DatetimeIndex.
- Read basic statistics such as mean, sum and standard deviation.
- Use
groupbyin pandas.
Three ways to summarize data
Most pandas summaries fall into one of three shapes.
- Aggregation collapses all rows into one value, for example
s.mean(). - Groupby collapses the rows of each group into one value per group.
- Window calculation keeps one result for every row. Each result is computed from that row and some of the rows around it.
The difference is in the output size and in which rows feed each result.
| Operation | Rows in the result | Rows used for each result |
|---|---|---|
| `s.mean()` | 1 | All rows |
| `df.groupby("key").mean()` | One per group | All rows of the group |
| `s.rolling(3).mean()` | Same as input | The current row and the 2 before it |
Because the output has the same length as the input, you can assign it straight back as a new column. This makes windows a natural fit for ordered data such as prices, sensor readings and daily sales. Smoothing a noisy series and tracking a running total are two typical uses.
How a window moves
A window is a set of consecutive rows that slides through the data. For each row, pandas selects the rows in the window, applies the statistic, and stores the result at that row's position.
Here is the same series summarized three ways.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.mean())
# 3.5
print(s.rolling(window=3).mean())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 3.0
# 4 4.0
# 5 5.0
print(s.expanding().mean())
# 0 1.0
# 1 1.5
# 2 2.0
# 3 2.5
# 4 3.0
# 5 3.5The plain mean() returns a single number. The rolling mean returns six values, each averaging the current row and the two before it. At row 2 the window holds 1, 2 and 3, so the result is 2.0. At row 3 the window holds 2, 3 and 4, so the result is 3.0.
The first two rolling results are NaN. A 3-row window needs three values, and rows 0 and 1 do not have enough rows behind them. These leading NaN values are expected behavior. A later chapter shows how to control them.
Two kinds of window
pandas offers two main window types.
- Rolling windows have a fixed size and slide. Each result looks back over the same number of rows (or the same time span, as you will see later).
- Expanding windows always start at the first row and grow by one row at each step. The last expanding result equals the plain aggregation. In the example above, the final value of
s.expanding().mean()is 3.5, the same ass.mean().
A third type, exponentially weighted windows, replaces the hard window edge with weights that fade for older rows. It comes near the end of the tutorial.
Common errors
- Expecting a value in every row. A rolling result needs a full window by default, so the first
window - 1rows areNaN. This is not a bug. - Confusing rolling with groupby. A groupby produces fewer rows and uses unrelated groups of rows. A rolling window produces one row per input row and uses neighbors in order. Row order therefore matters: sort your data first.
- Reading the window size as time.
rolling(3)means three rows, whatever the gaps between timestamps. A time span needs a string such as"3D", which a later chapter covers. - Forgetting that a window looks backward by default. The window ends at the current row, so each result includes the current value. This matters when you build features for prediction, and a later chapter on look-ahead leakage addresses it.
Exercise
A Series has 10 values. You call s.rolling(window=4).mean(). How many rows does the result have, and how many of them are NaN with default settings? Why does s.mean() give a different shape?
Show answer
The result has 10 rows, and the first 3 are NaN, because the first complete 4-row window ends at row 3 and rows 0 to 2 do not have enough rows. s.mean() is a plain aggregation that collapses all 10 values into a single number, while a window calculation returns one result per input row.
Exercise
For the Series [1, 2, 3, 4, 5, 6], what are the values of s.expanding().mean() at rows 0 and 3, and which rolling window size would make rolling().mean() give the same value at row 3?
Show answer
At row 0 the value is 1.0, and at row 3 it is 2.5 (the mean of 1, 2, 3 and 4). A rolling window of size 4 gives the same value at row 3, because it covers rows 0 to 3, which is everything the expanding window has seen so far.