Sub topic 2
Lagging a series with shift()
This chapter covers the core behavior of shift() on a time series: what it moves, what it leaves alone, and how to check that a lag is correct. It assumes you know basic Python, can create and index pandas Series and DataFrames, and are comfortable with DatetimeIndex and pd.date_range. Leads, NaN handling, diff(), freq, gaps and groups each get their own chapter, so this one only previews them.
What a lag is
A lag is an earlier value of a series placed next to a later one. A lag of 1 puts yesterday's value on today's row. Lags matter because many questions compare a value with its past. Examples are "did sales rise since yesterday?" and "can last week's demand predict this week's?"
In pandas, Series.shift(periods) produces a lag. It returns a new object in which every value has moved periods rows forward. The index does not move. Each timestamp keeps its label and receives the value that used to sit periods rows above it.
The basic call
Start with a small daily series.
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 previous day's value. On 2024-01-02 the original value was 12, and the shifted series shows 10, the value from 2024-01-01. The first row is NaN because no earlier row exists to supply a value. The last original value, 11, is dropped from the result because there is no later row to receive it.
Three details are worth noticing in this output:
- The index is identical to the original. Only the values moved.
- The dtype changed from
int64tofloat64. Integers cannot holdNaN, so pandas upcasts the whole series. A later chapter shows how to avoid this. - The series keeps its name and its
Freq: Dattribute.
The next diagram shows the alignment. Each arrow carries a value from its original row to the row below it.
Shift is positional
shift(1) means "one row", not "one day". For the series above these are the same thing, because the rows are exactly one day apart. If the rows were not evenly spaced, shift(1) would still move values by one row, and the lagged value might come from two or three days earlier.
The chapters on freq and on missing timestamps cover that case. For now, remember this rule: shift(n) counts rows in the object's current order.
The second half of that rule matters too. The order is the order the rows are stored in, not the order of the index. If a series is not sorted by time, shift produces lags that are wrong in time even though the code runs without error.
shuffled = s.iloc[[2, 0, 3, 1]]
print(shuffled.shift(1))This prints:
2024-01-03 NaN
2024-01-01 15.0
2024-01-04 10.0
2024-01-02 11.0
Name: sales, dtype: float64The row for 2024-01-04 received 10, which is the value from 2024-01-01. That is not "the previous day". Sort first:
print(shuffled.sort_index().shift(1))Make sort_index() (or sort_values on a date column) a habit before any shift, especially for data read from files, databases or joins. You can also check s.index.is_monotonic_increasing as a cheap guard.
Choosing the number of periods
periods can be any integer. A larger value moves values further and creates more NaN rows at the start.
lag2 = s.shift(2)
print(lag2)2024-01-01 NaN
2024-01-02 NaN
2024-01-03 10.0
2024-01-04 12.0
Freq: D, Name: sales, dtype: float64In general, shift(n) for a positive n creates exactly n leading NaN values. If n is greater than or equal to the length of the series, every value is NaN.
periods defaults to 1, so s.shift() equals s.shift(1). Spelling out the number makes code easier to read, and it makes a one-character change from 1 to -1 obvious in a code review.
Checking a lag by hand
Shifted data is easy to get subtly wrong, so it helps to verify one result against plain slicing. For a lag of 1, rows 1 onward of the shifted series should equal rows 0 through the second-to-last of the original.
check = (lag1.iloc[1:].to_numpy() == s.iloc[:-1].to_numpy()).all()
print(check)This prints True. The same idea works for any n: s.shift(n).iloc[n:] should match s.iloc[:-n]. Using .to_numpy() on both sides removes index alignment from the comparison, so you test the raw values and nothing else.
Shift returns a new object
shift() never changes the original. It returns a new Series, so assign the result if you want to keep it. A common mistake is calling s.shift(1) on its own line and expecting s to change. It will not, and there is no inplace option.
s.shift(1) # result is discarded
print(s.iloc[0]) # still 10Store the result under a new name or as a new column.
Shifting a DataFrame
Calling shift() on a DataFrame shifts every column at the same time. A frequent pattern is to place the original and its lags side by side.
frame = pd.DataFrame({
"sales": s,
"lag1": s.shift(1),
"lag2": s.shift(2),
})
print(frame) sales lag1 lag2
2024-01-01 10 NaN NaN
2024-01-02 12 10.0 NaN
2024-01-03 15 12.0 NaN
2024-01-04 11 15.0 12.0Wait: the lag2 value on 2024-01-03 should be 10, not NaN. The printed table above is wrong, and here is the correct one:
sales lag1 lag2
2024-01-01 10 NaN NaN
2024-01-02 12 10.0 NaN
2024-01-03 15 12.0 10.0
2024-01-04 11 15.0 12.0That mismatch is a good reason to run code rather than trust a mental model. Every row of lag2 equals the sales value two rows above it. Because the columns were built from the same index, pandas aligned them by label and there was no ambiguity.
You can also shift selected columns and assign the result back:
frame["sales_prev"] = frame[["sales"]].shift(1)["sales"]For a single column, frame["sales"].shift(1) is simpler. Use the double-bracket form when you want to shift several columns at once.
DataFrame.shift also accepts axis=1, which moves values sideways across columns instead of down rows. That is rarely what you want for time series, where time runs down the rows. If a shift seems to scramble your table, check that axis was not set.
What shift preserves and what it changes
| Property | After `shift(n)` |
|---|---|
| Index labels | Unchanged |
| Length | Unchanged |
| Values | Moved `n` rows forward |
| First `n` rows | `NaN` |
| Last `n` original values | Dropped |
| Integer dtype | Becomes float, because of `NaN` |
| Original object | Unchanged |
Because the index and length stay the same, a shifted series can be assigned straight back to the DataFrame it came from, or combined with the original in arithmetic. In a subtraction like s - s.shift(1), pandas aligns both sides on the index, so each row is compared with the row before it. That is the idea behind diff(), covered in a later chapter.
Common errors
- Unsorted data. The code runs and the numbers are wrong. Sort by time first.
- Gaps in the timestamps.
shift(1)then means "the previous row", which may be several days back. Regularize the index first, as a later chapter explains. - Multiple entities in one table. If a DataFrame stacks several stores or sensors, a plain
shift(1)pulls the last value of one group into the first row of the next. Usegroupbybefore shifting. - Forgetting the dtype change. Integer columns become floats after a shift. This matters when you later cast, merge on those values, or compare for equality.
- Discarded results.
shiftis not in place. Assign what it returns. - Wrong direction. A positive
periodsproduces a lag and a negative one produces a lead. If you want yesterday's value on today's row, use a positive number.
Putting it together
The following script builds a series, checks that it is sorted, creates two lags, and verifies one of them. It runs as shown.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
assert s.index.is_monotonic_increasing
frame = pd.DataFrame({
"sales": s,
"lag1": s.shift(1),
"lag2": s.shift(2),
})
assert (frame["lag2"].iloc[2:].to_numpy() == s.iloc[:-2].to_numpy()).all()
print(frame)The assertions turn the two assumptions that most often fail, sorted order and correct alignment, into checks that fail loudly instead of silently giving wrong features.
Summary
s.shift(n)moves valuesnrows forward and leaves the index alone.- The first
nrows becomeNaN, and the lastnoriginal values fall off the end. - Integer data becomes float because of the
NaNvalues. - Shifting counts rows, so order and spacing decide what a lag means.
shift()returns a new object. Assign the result.
Exercise
A DataFrame df has a daily DatetimeIndex and an integer column visits. You run df["prev"] = df["visits"].shift(2). How many rows of prev are NaN, what is the dtype of prev, and what must be true of the row order for prev to mean "the value from two days earlier"?
Show answer
Two rows are NaN, the first two. The dtype of prev is float64, because integers cannot hold NaN. For prev to mean "two days earlier", the rows must be sorted by time and have no missing days, so that two rows back is exactly two calendar days back.
Exercise
Given s = pd.Series([5, 7, 9, 4, 6]), write one line of code that builds a boolean check confirming s.shift(3) is correct for the rows where it has values.
Show answer
(s.shift(3).iloc[3:].to_numpy() == s.iloc[:-3].to_numpy()).all(). The shifted series has values from row 3 onward, and those must equal the original values from the start up to the third-from-last row. Here that compares [5, 7] with [5, 7], so the result is True.