Sub topic 2
Lagging a series with shift()
This chapter assumes you know basic Python, can create and index pandas Series and DataFrames, and have used pd.date_range to build a DatetimeIndex. It covers shift() as a lag and the model behind it. Leads, NaN handling, diff() and the other topics each have their own chapter.
What a lag is
A lag pairs each timestamp with an earlier observation. A lag of 1 means "the value one step before this one". Lags let you compare today with yesterday, or give a forecasting model past values as inputs.
In pandas, shift(periods) does this. It moves the values forward by periods rows and leaves the index where it is.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
lag1 = s.shift(1)
print(lag1)The output is:
2024-01-01 NaN
2024-01-02 10.0
2024-01-03 12.0
2024-01-04 15.0
Freq: D, Name: sales, dtype: float64Each date now shows the value from the previous row. The 10 that belonged to January 1 now sits on January 2. January 1 has nothing before it, so it gets NaN. The chapter on edge NaN values covers that in detail.
The working model
shift() has three properties to keep in mind.
- It moves by position, not by time.
shift(1)means "one row", whatever the gap between timestamps. This is correct for a regular index and wrong when dates are missing. - The index is untouched. Only the values move, so the result aligns with the original series on the same labels. That alignment is what makes lag columns easy to build.
- Values that move past the end are dropped. The last value, 11, appears nowhere in
lag1. The first slot has no source, so it is filled withNaN.
Because NaN is a float, an integer series becomes float64 after the shift. Here 10 became 10.0.
Using a lag as a column
The usual pattern is to store the lag next to the original values.
df = pd.DataFrame({
"sales": s,
"visits": [100, 110, 120, 130],
})
df["sales_lag1"] = df["sales"].shift(1)
df["sales_lag2"] = df["sales"].shift(2)
print(df)The output is:
sales visits sales_lag1 sales_lag2
2024-01-01 10 100 NaN NaN
2024-01-02 12 110 10.0 NaN
2024-01-03 15 120 12.0 10.0
2024-01-04 11 130 15.0 12.0Each row now holds the current value and the values from one and two steps earlier. You can compare them or pass them to a model.
If you call shift() on the whole DataFrame, every column moves by the same amount.
print(df[["sales", "visits"]].shift(1))Common errors
Assuming shift follows the dates
shift(1) on a series with a missing date gives you the value from the previous row. That may be two or more days earlier. If January 3 is missing, the January 4 row gets the January 2 value and looks like a one-day lag. The chapter on missing timestamps shows how to fix this with asfreq().
Shifting an unsorted index
shift() uses the current row order. It does not sort by date first. Check that the index is in time order before you shift.
s_sorted = s.sort_index()
lag1_safe = s_sorted.shift(1)If you shift s.sort_index(ascending=False), a row receives the value from the later date. That is a lead, not a lag, and nothing warns you.
Forgetting the result is a new object
shift() returns a new Series. It does not change s. Assign the result to a name or a column, or the lag is lost.
s.shift(1) # computed, then discarded
s_lagged = s.shift(1) # keptLosing integer types
If you need integers after a shift, you must deal with the NaN first. Without that step, the column stays float64. Filling edge values is covered in its own chapter.
Quick reference
| Call | Meaning | Result at the first date |
|---|---|---|
| `s.shift(1)` | Value from one row earlier | `NaN` |
| `s.shift(2)` | Value from two rows earlier | `NaN` (first two rows) |
| `s.shift(0)` | No movement | Original value |
Exercise
A daily series has the dates Jan 1, Jan 2 and Jan 4, with Jan 3 missing. You compute s.shift(1). What value does the Jan 4 row receive, and why might that be a problem?
Show answer
It receives the Jan 2 value, because shift(1) moves by one row, not one day. The result looks like "yesterday's value" but actually comes from two days earlier. Regularize the index with asfreq("D") first so the missing date appears as a row.
Exercise
Given df above, write one line that adds a column sales_lag3 holding sales from three rows earlier. How many NaN values will it contain?
Show answer
df["sales_lag3"] = df["sales"].shift(3). It contains three NaN values, one for each of the first three rows.