Sub topic 9
Shifting, differencing, and rolling windows
This chapter covers the operations that compare each observation with its neighbors in time. You will shift values forward and backward, compute differences and percent changes, and calculate rolling statistics over count-based and time-based windows.
It assumes you can build a DatetimeIndex and select with it, and that you know what a Timedelta is. It also assumes you are comfortable with Series and DataFrame basics.
Shifting values with shift
shift(n) moves the data by n rows while leaving the index in place. A positive n pushes values down, so each row sees the previous observation (a lag). A negative n pulls values up, so each row sees the next observation (a lead).
import pandas as pd
idx = pd.date_range("2024-03-01", periods=6, freq="D")
sales = pd.Series([100, 120, 90, 130, 150, 140], index=idx, name="sales")
out = pd.DataFrame({
"sales": sales,
"prev": sales.shift(1),
"next": sales.shift(-1),
"change": sales.diff(),
"pct": sales.pct_change(fill_method=None).round(3),
})
print(out)The first row of prev, change, and pct is NaN, because nothing comes before it. The last row of next is NaN for the same reason. The integer column sales becomes floating point in prev and next, since integers cannot hold NaN.
Each derived column answers a different question:
| Method | Computes | Result for a row |
|---|---|---|
| `shift(1)` | Value from the previous row | The lag |
| `diff()` | `x[t] - x[t-1]` | Absolute change |
| `pct_change()` | `x[t] / x[t-1] - 1` | Relative change |
All three take a number of rows. sales.diff(7) subtracts the value seven rows back, and sales.pct_change(7) gives the change relative to seven rows back. On a regular daily series, that is a week-over-week comparison.
Pass fill_method=None to pct_change, as above. In recent pandas versions the default behavior of forward-filling missing values before computing the change is deprecated. It also hides gaps that you probably want to see.
Shifting the index with freq
If you pass freq, shift changes the index labels and leaves the data alone. No rows are lost and no NaN appears.
shifted = sales.shift(1, freq="D")
print(shifted.index[0], shifted.iloc[0])
print(shifted.index[-1], shifted.iloc[-1])The value 100, which was labeled 2024-03-01, is now labeled 2024-03-02. The last row is labeled 2024-03-07. Use this form when you want to align two series on a date, for example "last week's value on this week's date". Then you can add the shifted series to the original and let index alignment do the matching.
Gaps make row-based shifting misleading
shift(1) counts rows, not time. When the index has missing dates, the row before a given row may be several days earlier.
irregular = sales.drop(pd.Timestamp("2024-03-03"))
print(irregular.shift(1))
print(irregular.shift(1, freq="D"))
print(irregular.asfreq("D").shift(1))The three results differ:
irregular.shift(1)gives 2024-03-04 the value 120, which belongs to 2024-03-02. That is a two-day lag, not a one-day lag.irregular.shift(1, freq="D")moves every label by exactly one day. The result has no value labeled 2024-03-03, and the entry for 2024-03-04 now shows the value from 2024-03-03, which does not exist. The missing day stays missing.irregular.asfreq("D").shift(1)first inserts the missing date withNaN, then shifts by rows. The row for 2024-03-04 becomesNaN, which correctly says "yesterday is unknown".
Differences between timestamps
diff() also works on a datetime column. The result is a Timedelta column, not a number, so you can compare it with a Timedelta directly. This is a quick way to find gaps in event data.
temps = pd.Series(
[10.0, 12.0, 11.0, 15.0, 14.0, 18.0],
index=pd.to_datetime([
"2024-03-01", "2024-03-02", "2024-03-03",
"2024-03-06", "2024-03-07", "2024-03-08",
]),
)
df = temps.rename("temp").rename_axis("when").reset_index()
gaps = df["when"].diff()
print(gaps)
print(df[gaps > pd.Timedelta("1D")])The first gap is NaT, the missing-time marker for datetimes and timedeltas. The comparison NaT > Timedelta is False, so the first row is never flagged. Only the row for 2024-03-06 appears, because it follows a three-day gap.
Rolling windows
A rolling window slides along the series and applies an aggregation to the values inside it. You create the window with rolling() and then call an aggregation such as mean(), sum(), min(), max(), std(), or median().
There are two kinds of window.
- Count-based:
rolling(3)uses the current row and the two before it. - Time-based:
rolling("3D")uses every row whose timestamp falls within the three-day span ending at the current row.
Both appear below on the temps series, which is missing 2024-03-04 and 2024-03-05.
print(temps.rolling(3).mean())
print(temps.rolling("3D").mean())The count-based result is NaN, NaN, 11.0, 12.667, 13.333, 15.667. The first two rows are NaN because a full window of three rows is not yet available. On 2024-03-06 the window holds the values from 2024-03-02, 2024-03-03, and 2024-03-06. That window spans four days, because the count ignores the gap.
The time-based result is 10.0, 11.0, 11.0, 15.0, 14.5, 15.667. It starts immediately because a time-based window defaults to min_periods=1. On 2024-03-06 the window contains only that day's reading, since the earlier readings are more than three days old.
Window boundaries
A time-based window is closed on the right and open on the left by default. The window ending 2024-03-06 covers the half-open interval (2024-03-03, 2024-03-06]. The reading from 2024-03-03 sits exactly three days earlier and is therefore excluded. The closed argument changes this:
print(temps.rolling("3D", closed="both").mean())With closed="both", the left edge is included, so the 2024-03-06 window now holds the readings 11.0 and 15.0 and gives 13.0. The other choices are "right" (the default), "left", and "neither".
Requiring enough data with min_periods
min_periods sets how many non-missing values a window needs before it returns a result. For a count-based window it defaults to the window size. For a time-based window it defaults to 1.
print(temps.rolling("3D", min_periods=2).mean())Windows with fewer than two observations now return NaN. A reading on a day with no recent neighbors, such as 2024-03-06, no longer produces a misleadingly "smoothed" value.
Rolling over a column
When the datetime values are in a column and not the index, use on:
print(df.rolling("3D", on="when")["temp"].mean())The on column must be datetime-typed and sorted in increasing order. Rolling over a time-based window on unsorted data raises a ValueError. The same requirement applies to a DatetimeIndex, which must be monotonic, so call sort_index() first if you are unsure.
Choosing the right tool
The choice between a count-based and a time-based window comes down to what the window should mean. A count-based window means "the last N observations" and is correct for regularly sampled data. A time-based window means "the last N days of observations" and is correct for irregular data such as events or sensor readings.
Common mistakes
- Reading the first rows as real results. The leading
NaNvalues fromshift,diff, and count-basedrollingare expected. Do not fill them with zero without thinking about it, because a zero change is a claim about the data. - Using
shift(365)for year-over-year comparison. It ignores leap years and missing days. Useshift(1, freq=...)with a calendar-aware offset, or compare against a resampled series. - Leaking the future. A negative shift or a centered window uses later values. Do not use these as features for predicting those later values. A centered window is created with
rolling(3, center=True). - Grouped data. When a frame has several entities (sensors, stores), a plain
shiftmoves values across entity boundaries. Group first, as indf.groupby("sensor")["temp"].shift(1).
Exercise
A daily series called visits is missing the date 2024-05-10. You call visits.shift(1) to get "yesterday's visits" for each row. Which row gets the wrong answer, and how do you fix it?
Show answer
The row for 2024-05-11 gets the value from 2024-05-09, which is two days earlier, because shift(1) moves by rows and the missing date has no row. Fix it by inserting the missing date before shifting: visits.asfreq("D").shift(1). The row for 2024-05-11 then becomes NaN, which correctly marks yesterday as unknown.
Exercise
Write an expression that gives the mean of the last three days for each reading in temps, but returns NaN when fewer than two readings fall inside the window. What does it return on 2024-03-06 for the data in this chapter?
Show answer
temps.rolling("3D", min_periods=2).mean(). On 2024-03-06 the window (2024-03-03, 2024-03-06] holds only one reading, so the result is NaN.