Sub topic 9
Shifting, differencing, and rolling windows
This chapter assumes you can create pandas Series and DataFrames, index them, and already know how to build a DatetimeIndex. It covers three tools that compare each observation with its neighbours in time: shifting, differencing, and rolling windows.
Shifting values with shift
shift() moves the data along the index while the index stays in place. A positive periods pushes values down (later in time), so each row sees the previous value. A negative value pulls future values back.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
s = pd.Series([10, 12, 11, 15, 14, 18], index=idx)
print(s.shift(1))
print(s.shift(-1))The first element of s.shift(1) and the last element of s.shift(-1) become NaN, because nothing exists to fill them. The integer dtype also becomes float for that reason.
Differencing and percent change
diff() subtracts the previous row. pct_change() divides that difference by the previous value. Both are shortcuts for expressions built on shift().
print(s.diff())
print(s.pct_change())
print((s - s.shift(1)).equals(s.diff()))On a datetime-valued column, diff() returns Timedelta values, which you can convert with .dt.total_seconds(), as in the earlier chapter on durations.
Shifting by time with freq
By default shift(n) moves by row count. If you pass freq, pandas moves the index labels instead and no NaN appears.
print(s.shift(1, freq="D"))
print(s.shift(1, freq="W"))This matters when rows are missing. If a day is absent, shift(1) reaches back to the previous existing row, which may be several days earlier. Shifting by freq="D" always means one calendar day.
gappy = s.drop(pd.Timestamp("2024-01-03"))
print(gappy.diff())
print(gappy - gappy.shift(1, freq="D").reindex(gappy.index))The first result compares 2024-01-04 with 2024-01-02. The second compares it with 2024-01-03 and gives NaN because that day does not exist.
Rolling windows
rolling() slides a window along the data and applies an aggregation to each window position.
print(s.rolling(3).mean())An integer window counts rows. The first window - 1 results are NaN, because the window is not full yet. Use min_periods to allow partial windows:
print(s.rolling(3, min_periods=1).mean())Time-based windows
With a DatetimeIndex, pass a duration string. The window then covers a span of time, not a count of rows, so irregular data is handled correctly.
print(gappy.rolling("3D").mean())By default the window is closed on the right: it includes the current timestamp and excludes the left edge. A "3D" window ending on 2024-01-04 covers January 2 (exclusive) to January 4 (inclusive). The index must be monotonic, meaning sorted in order, or pandas raises an error.
Row-based and time-based windows compared
| Window | Example | Window size | Handles gaps |
|---|---|---|---|
| Integer | `rolling(3)` | 3 rows | No, spans vary |
| Time offset | `rolling("3D")` | 3 days | Yes |
Common mistakes
- Using
shift(1)on data with missing rows and assuming it means "one day earlier". - Forgetting that
rolling(3)returnsNaNfor the first two rows. - Shifting by a negative amount and accidentally leaking future values into a model's features.
- Expecting
pct_change()to return percentages. It returns fractions, so 0.2 means 20%.
Exercise
A Series has a daily DatetimeIndex but the row for 2024-01-03 is missing. What is the difference between s.rolling(3).mean() and s.rolling("3D").mean() at 2024-01-04?
Show answer
rolling(3) averages the last three existing rows, which reach back to 2024-01-01 (rows for Jan 1, 2 and 4). rolling("3D") averages only rows inside the three-day span ending on Jan 4, which are Jan 2 and Jan 4, because Jan 1 falls outside it.
Exercise
How do you compute each day's change from exactly one calendar day earlier when some days are missing, and what do you get for a day whose predecessor is missing?
Show answer
Subtract the series shifted with freq="D", aligned to the original index: s - s.shift(1, freq="D").reindex(s.index). A day whose previous day is absent gets NaN.