Sub topic 2
Turning a Series into a Supervised Learning Table
This chapter assumes you know pandas (DataFrame, Series, DatetimeIndex), basic regression with scikit-learn's fit/predict, and the idea of train/test splits. Lag features, rolling windows and models come in later chapters. Here you build the table itself and see what the framing assumes.
The core idea
A supervised model needs rows of features X and a target y. A time series has only one column of values ordered in time. To get a table, you make each timestamp one row. The target is the value at that timestamp. The features are things you knew before that timestamp.
For a daily series, the simplest feature set is "yesterday's value". Shifting the series down by one row gives exactly that.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=8, freq="D")
s = pd.Series([10, 12, 11, 15, 14, 18, 17, 20], index=idx, name="y")
table = pd.DataFrame({"y": s, "lag_1": s.shift(1)})
print(table)The first row has NaN in lag_1, because nothing comes before the first observation. You drop such rows before training.
table = table.dropna()
X = table[["lag_1"]]
y = table["y"]Each row now reads: "given the value one day ago, predict today's value."
How the pieces fit
What this framing assumes
Treating each row as an independent example is a simplification. Standard regressors do not know that rows are ordered. Three assumptions follow.
- The index must be regular.
shift(1)means "one row back", not "one day back". If days are missing, the lag silently points to the wrong date. Uses.asfreq("D")to expose gaps, then decide how to fill them. - The relationship should be stable. The model learns a mapping from past to present. If the process changes, the mapping goes stale.
- Rows must be split by time. Shuffled rows would let the model train on the future and test on the past. A random
train_test_splitis therefore wrong here. Use a cut point instead.
cut = int(len(table) * 0.8)
train, test = table.iloc[:cut], table.iloc[cut:]
print(train.index.max(), "<", test.index.min())Common errors
| Error | Symptom | Fix |
|---|---|---|
| Shuffled split | Test score looks excellent, live accuracy is poor | Split at a date |
| Missing timestamps | Lags refer to the wrong day | Call `asfreq` and handle gaps |
| Not dropping `NaN` rows | Scikit-learn raises a `ValueError` for some models | Call `dropna()` after building features |
| Unsorted index | Shifts pair unrelated rows | Call `sort_index()` first |
Exercise
A daily series is missing the values for three days in the middle. You build lag_7 with s.shift(7) without calling asfreq. What goes wrong, and how do you fix it?
Show answer
shift(7) moves by seven rows, not seven days. After the gap, rows are less than seven days apart in time, so lag_7 holds a value from fewer than seven days earlier. Call s.asfreq("D") first so the missing days appear as NaN rows, then fill or handle them before shifting.