Worked Example: Building a Point-in-Time-Correct Training Set
Join labels to a nightly feature table with pandas.merge_asof, by key and backwards in time, choose allow_exact_matches and a tolerance, and measure how a naive date join inflates cross-validated AUC from 0.67 to 0.83 while production stays at 0.64.
Contentsand lesson path
On this page
- The problem
- Step 1: Labels and a nightly feature table
- Step 2: The naive join and the as-of join
- Step 3: Exact matches and stale rows
- Step 4: Measure the leak
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Preparation & Feature Engineering
- Auditing Raw Data Before You Model Concept · 20 min
- Imputation, Encoding and Scaling, Chosen by Model Family Concept · 25 min
- Worked Example: Features from Timestamps, Text and Group Aggregates Worked example · 25 min
- Lab: One Pipeline from Raw Rows to Predictions Lab · 30 min
- Worked Example: Building a Point-in-Time-Correct Training Set Worked example · 20 min
- Check: Preparing Data the Same Way Twice Knowledge check · 8 questions
What you will learn
- Engineer features from dates, free text and group aggregates computed only from data available at each prediction time (point-in-time-correct as-of joins), and keep only those that improve cross-validated scores.
01. The problem
A model predicts, when a parcel is booked, whether it will be late. Besides the parcel's weight, the most useful signal is how its depot has been doing lately: depots go through bad spells, from weather or staff shortages, that last a few days. A nightly job summarises each finished day per depot into a feature table, depot_daily, with the number of parcels and the share that were late. The job runs after midnight, and the row for a day is published at 02:00 the next morning. To keep the example small, assume every parcel's outcome is recorded by the end of its booking day.
The training set needs one row per parcel, with the depot features as they were known at booking time. That is a point-in-time-correct training set: every feature value is one the model could have seen at the moment of prediction, no later. The tool is an as-of join. The warning sign of getting it wrong is a cross-validated score that production never reaches. This example builds both versions and measures the gap. Tested with Python 3.12, NumPy 2.5, pandas 3.1 and scikit-learn 1.9; run every script in one folder.
02. Step 1: Labels and a nightly feature table
The generator simulates six depots over 150 days with 10 to 20 parcels per depot per day. Each depot has a hidden "spell" value that drifts from day to day; a bad spell makes lateness more likely for several days in a row. The nightly table holds two kinds of time: day, the day a row describes, and published_at, the moment the row became available.
"""Write parcels.csv (labels) and depot_daily.csv (a nightly feature table)."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(11)
days = pd.date_range("2026-01-01", periods=150, freq="D")
depots = ["D1", "D2", "D3", "D4", "D5", "D6"]
# Each depot has good and bad spells (weather, staff) that last a few days
spell = np.zeros((len(days), len(depots)))
for t in range(1, len(days)):
spell[t] = 0.6 * spell[t - 1] + rng.normal(0, 0.8, len(depots))
rows = []
for t, day in enumerate(days):
for j, depot in enumerate(depots):
k = int(rng.integers(10, 21))
booked = day + pd.to_timedelta(np.sort(rng.integers(0, 24 * 60, k)), unit="min")
weight = rng.lognormal(0.8, 0.6, k).round(2)
p = 1 / (1 + np.exp(-(-1.2 + 1.5 * spell[t, j] + 0.1 * weight)))
rows.append(pd.DataFrame({"depot": depot, "booked_at": booked,
"weight_kg": weight,
"late": (rng.random(k) < p).astype(int)}))
parcels = pd.concat(rows, ignore_index=True)
parcels.insert(0, "parcel_id", [f"P{i:05d}" for i in range(len(parcels))])
# The nightly job summarises each finished day and publishes at 02:00 next morning
daily = (parcels.assign(day=parcels["booked_at"].dt.normalize())
.groupby(["depot", "day"], as_index=False)
.agg(parcels=("late", "size"), late_share=("late", "mean")))
daily["published_at"] = daily["day"] + pd.Timedelta(days=1, hours=2)
parcels.to_csv("parcels.csv", index=False)
daily.to_csv("depot_daily.csv", index=False)
print("parcels:", parcels.shape, "| depot_daily:", daily.shape)
print(daily.head(3).round({"late_share": 3}).to_string(index=False))parcels: (13622, 5) | depot_daily: (900, 5)
depot day parcels late_share published_at
D1 2026-01-01 16 0.125 2026-01-02 02:00:00
D1 2026-01-02 16 0.375 2026-01-03 02:00:00
D1 2026-01-03 10 0.700 2026-01-04 02:00:00Keep published_at in any feature table you build. Without the time at which a value became available, a table cannot be joined correctly, however carefully the values themselves were computed.
03. Step 2: The naive join and the as-of join
The naive join is the one most people write first: match on depot and calendar day. Each parcel then receives its own day's late share, which includes its own outcome and those of parcels booked later that day, from a row published the next morning.
The correct join uses pd.merge_asof. For each row on the left, it finds the last row on the right with the same by key whose on time is earlier (or equal, by default), and attaches it. Here the left table is the parcels, matched on booked_at; the right table is depot_daily, matched on published_at, not on day. direction="backward" (the default) searches only the past. Both tables must be sorted by their time column, or pandas raises ValueError: left keys must be sorted; the by column does not need sorting.
import pandas as pd
parcels = pd.read_csv("parcels.csv", parse_dates=["booked_at"])
daily = pd.read_csv("depot_daily.csv", parse_dates=["day", "published_at"])
def naive_join(parcels, daily):
"""Join on depot and calendar day: the row for the day the parcel was booked."""
left = parcels.assign(day=parcels["booked_at"].dt.normalize())
return left.merge(daily, on=["depot", "day"], how="left")
def asof_join(parcels, daily):
"""For each parcel, the latest row of its depot published before booking."""
return pd.merge_asof(
parcels.sort_values("booked_at"),
daily.sort_values("published_at"),
left_on="booked_at", right_on="published_at", by="depot",
direction="backward", # only rows from the past
allow_exact_matches=False, # published at 02:00 is not usable at 02:00
)
if __name__ == "__main__":
pick = ["P00183", "P00185", "P00191"] # depot D1, booked on 3 January
cols = ["parcel_id", "booked_at", "day", "published_at", "late_share"]
for name, join in [("naive", naive_join), ("as-of", asof_join)]:
out = join(parcels, daily)
print(f"{name} join")
print(out.loc[out["parcel_id"].isin(pick), cols].to_string(index=False))
future = out["published_at"] > out["booked_at"]
print(f"rows using a value published after booking: {future.sum()}\n")naive join
parcel_id booked_at day published_at late_share
P00183 2026-01-03 01:30:00 2026-01-03 2026-01-04 02:00:00 0.7
P00185 2026-01-03 04:06:00 2026-01-03 2026-01-04 02:00:00 0.7
P00191 2026-01-03 21:18:00 2026-01-03 2026-01-04 02:00:00 0.7
rows using a value published after booking: 13622
as-of join
parcel_id booked_at day published_at late_share
P00183 2026-01-03 01:30:00 2026-01-01 2026-01-02 02:00:00 0.125
P00185 2026-01-03 04:06:00 2026-01-02 2026-01-03 02:00:00 0.375
P00191 2026-01-03 21:18:00 2026-01-02 2026-01-03 02:00:00 0.375
rows using a value published after booking: 0All three parcels were booked at depot D1 on 3 January. The naive join gives each of them 0.7, the share for 3 January, published at 02:00 on 4 January, hours or nearly a day after the bookings. Every one of the 13,622 rows uses a value from its own future.
The as-of join gives a different answer per booking time. P00183, booked at 01:30, gets the row for 1 January, because the row for 2 January is published only at 02:00 on 3 January, half an hour later. P00185 and P00191, booked after 02:00, get 2 January's row. No row uses a value published after its booking, and that count makes a good assertion to keep in the training code. Note that merge_asof returns rows in the order of the left table you pass, here sorted by time.
04. Step 3: Exact matches and stale rows
Two parameters decide the edge cases. allow_exact_matches controls a right row whose time equals the left time exactly: True (the default) treats it as available, False requires it to be strictly earlier. tolerance sets how old a match may be; an older one gives NaN. Three requests show both.
import pandas as pd
daily = pd.DataFrame({
"depot": ["D1", "D1"],
"published_at": pd.to_datetime(["2026-03-02 02:00", "2026-03-03 02:00"]),
"late_share": [0.20, 0.55],
})
requests = pd.DataFrame({
"depot": ["D1", "D1", "D1"],
"booked_at": pd.to_datetime(["2026-03-03 02:00", "2026-03-03 09:00",
"2026-03-08 09:00"]), # the job stopped on 4 March
})
options = {
"exact allowed": dict(allow_exact_matches=True),
"strictly before": dict(allow_exact_matches=False),
"strictly before, 36h": dict(allow_exact_matches=False,
tolerance=pd.Timedelta(hours=36)),
}
out = requests.copy()
for name, kwargs in options.items():
joined = pd.merge_asof(requests, daily, left_on="booked_at",
right_on="published_at", by="depot", **kwargs)
out[name] = joined["late_share"]
print(out.to_string(index=False))depot booked_at exact allowed strictly before strictly before, 36h
D1 2026-03-03 02:00:00 0.55 0.20 0.20
D1 2026-03-03 09:00:00 0.55 0.55 0.55
D1 2026-03-08 09:00:00 0.55 0.55 NaNThe booking at exactly 02:00 on 3 March gets the new value 0.55 when exact matches are allowed, and the previous 0.20 when they are not. Which is right depends on what the timestamp means. If published_at is when the job started writing, or the table reaches the serving store with a delay, the row is not readable at that instant, and False is the honest choice. The cost of being cautious is at most one missed update right at the boundary, so choose False when in doubt.
The booking on 8 March shows a quieter failure. The nightly job stopped after 3 March, yet without a tolerance the join keeps attaching the 3 March value as if it were fresh. With tolerance=pd.Timedelta(hours=36), which suits a daily job, the stale match becomes NaN, and the pipeline's imputer and missing indicator handle it like any gap. Use the same rule in serving: if the online feature store returns stale values without saying so, train with the same staleness, or make both sides refuse old values. Avoid direction="forward" and "nearest" for features; they can pick a row from after the prediction.
One pandas 3 detail: the two time columns must have the same dtype. Times parsed from CSV are datetime64[us] in pandas 3, while values built elsewhere may be datetime64[ns], and merge_asof then raises MergeError: incompatible merge keys. Align them first, for example with .dt.as_unit("us").
05. Step 4: Measure the leak
Now measure what the leak does. Train a logistic regression on the first 100 days, once with each training set, and cross-validate it with TimeSeriesSplit. Then score both on the last 50 days, "production", with features built the only way serving can build them: as-of, from rows already published.
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from joins import asof_join, daily, naive_join, parcels
FEATURES = ["late_share", "weight_kg"]
CUTOFF = pd.Timestamp("2026-04-11") # train on the first 100 days
def model():
return make_pipeline(SimpleImputer(strategy="median"), LogisticRegression())
# Serving can only read rows that were already published: that is the as-of join
served = asof_join(parcels, daily)
production = served[served["booked_at"] >= CUTOFF]
print(f"{'training set':<12} {'CV AUC (past days)':>19} {'prod. AUC':>10}"
f" {'prod. log loss':>15}")
for name, join in [("naive", naive_join), ("as-of", asof_join)]:
data = join(parcels, daily).sort_values("booked_at", ignore_index=True)
train = data[data["booked_at"] < CUTOFF]
cv = cross_val_score(model(), train[FEATURES], train["late"],
cv=TimeSeriesSplit(5), scoring="roc_auc")
fitted = model().fit(train[FEATURES], train["late"])
p = fitted.predict_proba(production[FEATURES])[:, 1]
auc, loss = roc_auc_score(production["late"], p), log_loss(production["late"], p)
print(f"{name:<12} {cv.mean():>13.3f} ± {cv.std():.3f} {auc:>10.3f} {loss:>15.3f}")training set CV AUC (past days) prod. AUC prod. log loss
naive 0.829 ± 0.014 0.635 0.731
as-of 0.666 ± 0.017 0.636 0.629The naive training set promised a cross-validated AUC of 0.829 and delivered 0.635. The as-of set promised 0.666 and delivered 0.636. Both models end up ranking production parcels about equally well, because both rely on the same depot signal, but only one of them told the truth beforehand. The naive model is also worse where probabilities matter: its production log loss is 0.731 against 0.629. It learned that late_share almost decides the outcome, which was true of a same-day value that includes the parcel itself, and it now applies that confidence to yesterday's value. Any threshold or business case built on 0.829 would be wrong.
Cross-validation could not catch this. Every fold was cut from the same leaky table, so the validation rows had leaky features too, and the folds agreed with each other (0.829 ± 0.014). Consistent folds measure stability, not the absence of leakage. The checks that do catch it are structural: join on availability time, assert that no feature time is later than the prediction time, and validate on a later period with features built exactly as serving builds them.
06. Common mistakes
07. Check your understanding
08. Apply it
Apply this to the group aggregate in your practice project.
- Store the aggregate as a feature table with an entity key, the time each value describes, and the time it became available.
- Build the training set with
pd.merge_asof(..., by=<key>, direction="backward")on the availability time, decide onallow_exact_matchesand atolerance, and add an assertion that no joined value became available after the prediction time. - Build a naive version with a date join, and report both its cross-validated score and its score on a later period with as-of features. Put the two numbers side by side in your notes.
09. Review prompt
Without looking back, answer in your own words:
- What makes a training set point-in-time correct?
- For each left row, which right row does
merge_asofwithdirection="backward"and abykey return? - When should
allow_exact_matchesbeFalse, and what does atoleranceprotect against? - Why did consistent cross-validation folds fail to reveal the leak, and which checks would have caught it?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.