Sub topic 2
Turning a series into a supervised learning table
Gradient boosting models expect a table of rows and columns. A time series is a single column of values ordered in time. This chapter shows how to convert one into the other, what the conversion assumes, and where it breaks. It assumes you know pandas (Series, DataFrame, DatetimeIndex), the scikit-learn fit/predict interface, and the idea of a train/test split.
The core idea
A supervised model learns a function from input features X to a target y. For forecasting, the target is the value we want to predict at time t. The features are things we know before t: earlier values of the series, summaries of recent history, and facts about the calendar.
Each time step becomes one row:
- The target
yis the value at timet. - The features describe what was known at
t - 1or earlier, plus anything known in advance aboutt, such as its day of the week.
After this change, forecasting is ordinary regression. Any regressor can be used, including gradient boosting.
A worked example
Take seven daily sales values.
import pandas as pd
s = pd.Series(
[10, 12, 11, 15, 14, 18, 17],
index=pd.date_range("2026-01-01", periods=7, freq="D"),
name="sales",
)
table = pd.DataFrame({"y": s, "lag_1": s.shift(1), "lag_2": s.shift(2)})
print(table)Output:
y lag_1 lag_2
2026-01-01 10.0 NaN NaN
2026-01-02 12.0 10.0 NaN
2026-01-03 11.0 12.0 10.0
2026-01-04 15.0 11.0 12.0
2026-01-05 14.0 15.0 11.0
2026-01-06 18.0 14.0 12.0
2026-01-07 17.0 18.0 14.0The output above is illustrative of the layout. Run the code to see exact values.
s.shift(1) moves every value down one row. On 2026-01-03, lag_1 holds the value from 2026-01-02. The model sees yesterday and must predict today. The first rows contain NaN because there is no earlier data, so they are usually dropped.
What the framing assumes
Treating each row as an independent example is a convenience, not a fact. The rows overlap heavily: row t and row t + 1 share most of their lag values. Three assumptions follow.
- Regular spacing.
shift(1)means "one row back", not "one day back". If the index has gaps or irregular timestamps, a lag silently refers to the wrong period. Calls.asfreq("D")first so that missing days appear as explicitNaNrows, then decide how to fill them. - A stable relationship. The model learns how the past maps to the next value. If that relationship changes (a price change, a new store, a pandemic), what it learned no longer holds.
- Features available at prediction time. Every feature must be known when the forecast is made. A column you only learn after the fact cannot be used. This is the source of target leakage, covered in a later chapter.
Rows are not independent
Because neighbouring rows overlap and values are autocorrelated (a value resembles its recent past), you cannot shuffle the rows for a train/test split. A random split would place a row from Tuesday in the training set and the rows on either side of it in the test set. The model would look accurate because it has effectively seen the answer's neighbours. Always split by time: train on the earlier rows, test on the later ones.
cut = int(len(table.dropna()) * 0.8)
clean = table.dropna()
train, test = clean.iloc[:cut], clean.iloc[cut:]Later chapters build on this with walk-forward validation.
Choosing what goes in the table
The lag columns are one kind of feature. A typical table combines several:
| Feature type | Example | Known at forecast time because |
|---|---|---|
| Lag | `lag_7` | It is a past value of the target |
| Rolling window | mean of the last 7 values, shifted by one | It summarizes past values only |
| Calendar | day of week, month | The calendar is known in advance |
| External | planned promotion flag | Only if the plan is known ahead |
Each type has its own chapter. For now, the rule to keep is that a feature belongs in the table only if you could compute it on the day you make the forecast.
Building the table with a helper
It is worth wrapping the construction in a function. The same code must later run on new data, and one definition keeps training and prediction consistent.
import pandas as pd
def lag_table(s: pd.Series, lags=(1, 2, 7)) -> pd.DataFrame:
if not isinstance(s.index, pd.DatetimeIndex):
raise TypeError("s needs a DatetimeIndex")
if s.index.freq is None:
raise ValueError("set a frequency first, for example s.asfreq('D')")
df = pd.DataFrame({"y": s})
for k in lags:
df[f"lag_{k}"] = s.shift(k)
return df.dropna()
sales = pd.Series(
range(30),
index=pd.date_range("2026-01-01", periods=30, freq="D"),
name="sales",
)
print(lag_table(sales).head(3))The function refuses a series without a regular frequency. This catches the most common silent error in this framing: lags that do not mean what you think.
Common errors
- Using
shift(-k). A negative shift brings future values into the row. It is occasionally right for building a target, but never for a feature. - Shuffling before splitting.
train_test_splitshuffles by default. Passshuffle=False, or slice by position as shown above. - Dropping
NaNrows too early. Drop them after all features are built, or you may remove more history than needed. Dropping also shortens the usable series by the largest lag, so a 14-step lag costs 14 rows. - Forgetting the lost rows. On a short series, large lags can leave very little training data. Count the rows after
dropna(). - Ignoring gaps. A missing day shifts every later lag by one row unless the index is regularized first.
Checking your table
Before fitting anything, inspect the table with two quick checks.
- Pick one row and verify by hand that each feature equals the value you expect from an earlier date.
- Confirm the index is increasing and evenly spaced:
table.index.is_monotonic_increasingandtable.index.to_series().diff().nunique() == 1.
These checks take seconds and catch most framing mistakes.
Exercise
A series has daily values, but 2026-03-10 is missing from the index. You build lag_1 with s.shift(1) without calling asfreq("D"). What goes wrong for the row dated 2026-03-11, and how do you fix it?
Show answer
Without a row for 2026-03-10, shift(1) gives 2026-03-11 the value from 2026-03-09, which is two days earlier, not one. The lag silently means something different on that row. Fix it by calling s.asfreq("D") so the missing day becomes a NaN row, then fill or drop it deliberately.
Exercise
Why is train_test_split(X, y, test_size=0.2) with its default settings a poor choice for a lag-feature table?
Show answer
It shuffles rows. Test rows then sit between training rows, and because neighbouring rows share lag values and are autocorrelated, the model is effectively evaluated on points it has seen the neighbours of. The score is too optimistic. Split chronologically instead, for example with shuffle=False or iloc slicing.