Start learning free

LESSON 110 OF 165 · MACHINE LEARNING: TIME SERIES

Yesterday as a Feature: Lags in Python

Practice

To predict this week's revenue, a model needs features, and it can only use what is known before the week starts. The most useful known number is recent revenue: last week's, or the one from about a month ago. A lag is such a past value, put as a column next to each week.

series.shift(n) gives back the same values moved down n rows, so each row gets the value from n rows before. The first n rows have nothing to take, so they get NaN, pandas' mark for a missing value.

visits = pd.Series([5, 8, 6])
visits.shift(1)   # NaN, 5.0, 8.0
visits.shift(2)   # NaN, NaN, 5.0

A model can't learn from rows with a NaN: table.dropna() gives back only the rows with no missing value. Then the lag columns are the features, X, and this week's revenue is what to predict, y. .shape gives back the number of rows (and of columns, for a table).

Your program must print:

            revenue  lag_1  lag_4
date                             
2026-01-04       23    NaN    NaN
2026-01-11      215   23.0    NaN
2026-01-18       16  215.0    NaN
2026-01-25        0   16.0    NaN
2026-02-01      298    0.0   23.0
2026-02-08      109  298.0  215.0
X: (44, 2) y: (44,)

Your task: the starting code builds table with one column, revenue, one row per week. Below the blank line, add lag_1 (last week's revenue) and lag_4 (the revenue of 4 weeks before), print the first 6 rows, drop the rows with a NaN, then keep the two lags in X and the revenue in y, and print their shapes.


Assignment
Follow the Coding Tutorial to turn last week's and last month's revenue into feature columns, ready for a model.


Hint
Follow one number: 215, the revenue of 2026-01-11, shows up in lag_1 one row down and in lag_4 four rows down. The first 4 weeks have no lag_4, so dropna leaves 44 rows.


STEP 1 OF 7
    Ctrl + Enter to check

    Ts Lags in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free