Sub topic 1
Shifting and Lagging Time Series in pandas
Prerequisites
Assume you know basic Python, pandas Series and DataFrame objects, and DatetimeIndex. A time series stores values in time order. Its index identifies when each value occurred.
A time series with a `DatetimeIndex`
Create dates with pd.date_range() and use them as the index. The index lets pandas align values by time.
import pandas as pd
sales = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(sales)The series has one observation per day. The freq="D" argument means daily frequency.
Lagging a series with `shift()`
shift(1) moves values one row forward. The value for January 2 becomes the value recorded on January 1. This creates a one-period lag.
lag1 = sales.shift(1)
print(lag1)The first date has no earlier row, so pandas inserts NaN, which represents a missing numeric value.
For a DataFrame column, use the same method: df["sales"].shift(1). Larger positive periods create longer lags.
Looking ahead with negative periods
A negative period creates a lead. shift(-1) moves each value one row backward, so each date receives the next date's value.
lead1 = sales.shift(-1)
print(lead1)The final date becomes NaN because no later row exists. Leads are useful for analysis, but using them as forecasting inputs would expose future information.
Why `NaN` appears and how to fill it
Shifting creates an empty edge because values move beyond the available index. Pass fill_value to replace that edge:
filled = sales.shift(1, fill_value=0)
print(filled)This treats the missing previous value as zero. Choose that replacement only when zero has a valid meaning. Otherwise, keep NaN, remove incomplete rows, or use a domain-specific value.
Exercise
What does sales.shift(-1) do, and where does its NaN appear?
Show answer
It creates a one-period lead by moving values backward. NaN appears at the final date because there is no next observation.