Sub topic 3
Looking ahead with negative periods
This chapter assumes you know basic Python, can create and index pandas Series and DataFrames, and are comfortable with DatetimeIndex and pd.date_range. It also assumes you have seen shift(1) produce a lag. Here you will use the other direction: a negative periods value, which produces a lead.
What a negative period does
A lag shows each row the value from earlier in time. A lead does the opposite: each row shows the value from later in time. In pandas you ask for a lead by passing a negative number to shift().
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
lead1 = s.shift(-1)
print(lead1)The output is:
2024-01-01 12.0
2024-01-02 15.0
2024-01-03 11.0
2024-01-04 NaN
Freq: D, Name: sales, dtype: float64The row labeled 2024-01-01 now holds 12, which is the original value from 2024-01-02. Every value moved one row toward the top, and the last label has nothing left to pull from, so it becomes NaN.
The sign of periods sets the direction, and its size sets the distance.
| Call | Meaning | Row at time t holds |
|---|---|---|
| `s.shift(1)` | lag of one row | value from t - 1 row |
| `s.shift(0)` | no movement | value from t |
| `s.shift(-1)` | lead of one row | value from t + 1 row |
| `s.shift(-3)` | lead of three rows | value from t + 3 rows |
The values are the same ones you started with, and only their alignment against the index changes. The index itself is never touched when you call shift() without freq.
Lead and lag are the same operation
s.shift(-1) is not a separate feature. Shifting by -1 and shifting by 1 are the same mechanism with opposite signs. Two consequences follow from this.
First, the NaN rows move to the other end. A lag leaves NaN at the start of the series, and a lead leaves NaN at the end. With shift(-k) the last k rows are NaN, because those rows have no value k steps in the future.
Second, if you shift by more rows than the series has, every value is NaN:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(s.shift(-10).isna().all())This prints True. pandas does not raise an error, so a window that is too large fails silently. Check the NaN count when you choose a large horizon.
Why the result is float
The input series holds integers, but shift(-1) returns floats (12.0, 15.0, and so on). Standard NumPy integers cannot represent a missing value, so pandas converts the column to float64 to make room for NaN. If you need to keep integers, convert to the nullable Int64 type first. Its missing marker is <NA>:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(s.astype("Int64").shift(-1))The output is:
2024-01-01 12
2024-01-02 15
2024-01-03 11
2024-01-04 <NA>
Freq: D, Name: sales, dtype: Int64Filling the gap, and why zero is risky
You can use fill_value with a lead the same way you do with a lag. It replaces the empty edge and keeps the integer dtype:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(s.shift(-1, fill_value=0))The last row is now 0, and the dtype stays int64.
Be careful with this for leads. A lead at the end of the series means "we do not know the future yet". Writing 0 there claims that the next value is zero. If a model or a report treats the filled row as real data, it will learn from or display something false. A missing future is better kept as NaN, then removed or masked explicitly.
Common uses for leads
A lead answers questions of the form "what happens next?" There are three typical uses.
Building a prediction target
In supervised forecasting, you want to predict tomorrow from today. Put today's value in the feature column, and put tomorrow's value, a lead, in the target column:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
data = s.to_frame()
data["next_day"] = data["sales"].shift(-1)
print(data)
train = data.dropna(subset=["next_day"])
print(train)The first print shows four rows, with NaN in next_day on 2024-01-04. After dropna, three rows remain. The dropped row is not an error. It is the one row whose answer is not yet known, so it cannot be used for training. It is, however, the row you would use to make the next real prediction, so keep a copy of it before you drop it.
Forward-looking change
To measure how much the value will change from now to the next row, subtract the current value from the lead:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
forward_change = s.shift(-1) - s
print(forward_change)
print(forward_change.equals(-s.diff(-1)))The values are 2.0, 3.0, -4.0 and NaN. diff(-1) computes s - s.shift(-1), which is the opposite sign, so negating it matches. The second print shows True. The next chapters cover diff() and pct_change() in full. The point here is that both accept negative periods.
Several horizons at once
For a multi-step forecast, build one target column per horizon:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
horizons = pd.DataFrame({
"sales": s,
"lead1": s.shift(-1),
"lead2": s.shift(-2),
})
print(horizons)The output is:
sales lead1 lead2
2024-01-01 10 12.0 15.0
2024-01-02 12 15.0 11.0
2024-01-03 15 11.0 NaN
2024-01-04 11 NaN NaNEach extra step ahead costs one more row of usable data at the end. A model that predicts seven days ahead loses the last seven rows from training.
Leads change the meaning of a column
A lagged column is safe to use as a model input, because the past is known when you predict. A lead is the opposite. It contains information from after the row's own timestamp.
Pitfall: the index must be sorted
shift() moves values by row position. It does not look at the timestamps. So the direction of "forward" is the direction of the rows, and that matches time only if the index is in ascending order.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
reversed_s = s.sort_index(ascending=False)
print(reversed_s.shift(-1))In the reversed series, the first row is 2024-01-04. shift(-1) gives it the value of the next row, which is 2024-01-03 (15). That is the previous day, not the next one. The result is a lag, even though you wrote a lead.
The same problem appears when data comes from a database or a merge in unspecified order. Sort before shifting:
sorted_s = reversed_s.sort_index()
print(sorted_s.shift(-1))This restores the output you saw at the start of the chapter. In a DataFrame, call df.sort_values("date") or df.sort_index(), depending on where the timestamps are.
Pitfall: gaps and groups
Two more cases break the idea that "one row ahead means one day ahead".
- If a timestamp is missing,
shift(-1)jumps over the gap. A row dated Jan 2 may receive the value from Jan 4. Chapter 7 shows how to restore the missing dates withasfreq()first. - If the data holds several entities, such as stores or sensors, stacked in one table, a lead on the last row of store A pulls the first row of store B. Chapter 8 shows how to prevent this with
groupby().shift().
You will usually need both fixes together when you build real forecasting data.
Shifting the index instead
Instead of moving values, you can move the labels. With freq, shift() leaves the values alone and shifts the index:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(s.shift(-1, freq="D"))The values stay 10, 12, 15 and 11, but the index now runs from 2023-12-31 to 2024-01-03. No NaN is created. This is a different operation, which the plan covers in its own chapter. It is useful for aligning two series on different clocks, not for building leads and lags.
Quick checks
After you create a lead, a few checks catch most mistakes:
- Confirm that the index is sorted in ascending order with
s.index.is_monotonic_increasing. - Count the missing values. For
shift(-k)you expect exactlyknewNaNvalues at the end, per group if you are grouping. - Spot check one row by hand. Pick a date, find the value
krows later in the original data, and compare it with the shifted column. - Name the column after its direction, for example
next_dayorsales_lead1. A clear name prevents someone from using a lead as a feature by mistake.
Exercise
A series s has a DatetimeIndex of 5 consecutive days. You compute t = s.shift(-2). How many values of t are NaN, where are they, and why would using t as a model input be a problem?
Show answer
Two values are NaN, in the last two rows, because those rows have no value two rows later. Using t as a model input is a problem because each row then contains the value from two days in the future, which is not known at prediction time. This is lookahead leakage. A lead belongs in the target column, not in the features.
Exercise
Given s = pd.Series([5, 8, 6], index=pd.date_range("2024-03-01", periods=3, freq="D")), write one expression that gives each day's change to the next day, and say what it returns.
Show answer
s.shift(-1) - s returns 3.0, -2.0 and NaN. The first two values are the change from each day to the following day (8 - 5 and 6 - 8). The last is NaN because there is no next day after 2024-03-03. An equivalent expression is -s.diff(-1).
Exercise
You load a table of daily data that is sorted newest first, and run shift(-1) hoping to get the next day's value. What do you actually get, and how do you fix it?
Show answer
You get the previous day's value, because shift works by row position and the next row is an earlier date. Fix it by sorting in ascending time order, for example with sort_index(), before shifting. You can also use shift(1) on the descending data, but sorting first is clearer.