Learning path: Data and Features in Production · Step 4 of 8
Point-in-Time Correctness: Join Features as of Each Event with merge_asof
A feature may only use what was known at the moment of the prediction. Create the leak with a plain merge of today's balance, fix it with pandas merge_asof, and compare the two tables and their scores on synthetic payment data.
What you will learn
- Explain why each training row needs its own cutoff: what was known at that event's moment
- Spot the leak a plain merge with today's value creates
- Join the value as of each event with pandas merge_asof, by customer, direction backward
- Check a joined table by counting rows whose value comes from the future
Before you start
- Time Splits and Group Splits
- Train-Test Split and Data Leakage
- pandas merge basics
Tom is placing a bet on Saturday's match. Nobody knows who will win yet. But Tom has Sunday's paper, and the result is right there on the front page. So Tom never loses.
Next Saturday there's no Sunday paper, and all that skill is gone. The skill was never in Tom. It was in the paper.
In machine learning, Sunday's paper is a feature from the future, and Tom is our model. The rule this lesson is about:
A feature can only use what was known at the moment of the prediction. And every row has its own moment.
A single cutoff date, like the time split in Time Splits and Group Splits, isn't enough here. Every event happens at its own time, so for every row we ask: what did we know right then?
A small synthetic data set
To see the bug clearly we make the data ourselves. It's synthetic: these aren't real customers. Each customer has a balance that drifts over time and a few payments that fall due. A low balance and a big bill make a missed payment more likely. That's the real signal. An excerpt from inside the customer loop in make_data.py:
# the real signal: low balance and a big bill, more misses
risk = np.log(balance / 2000) * -0.8 + (amount - 275) / 300
missed = rng.random() < 1 / (1 + np.exp(1.6 - risk))
dues.append((day, amount, int(missed)))
# what happens AFTER the due date, because of the outcome
after = balance * (1 - hit) if missed else balance - amount
pending.append((day + 1, max(after, 10.0)))
Now this line matters: a missed payment halves the balance the next day (HIT = 0.5). We built that in on purpose. A paid one just takes the amount out.
balance_history (6697, 3)
events (1198, 4)
missed 0.263
balance_history has a row each time a balance changes (customer, changed_at, balance). events has a row for each payment due, and each event's time is our prediction moment. 26.3% of payments are missed.
The leak, on one customer
On 3 February a payment is due for customer C001. At that moment the balance is 2,401. The customer misses, so the next day the balance falls to 1,201. The year rolls on, and today the balance is 724.
Now join today's balance onto that old event. The model sees 724 on a day when the balance was 2,401. And that low number is partly there because they missed. The answer is sitting inside the feature.
The wrong way: today's value on every event
import pandas as pd
def join_today(events, history):
"""WRONG: today's balance on every event, however old."""
latest = history.groupby("customer").tail(1)
return events.merge(latest, on="customer")
wrong join, customer C001
event_time missed balance
2025-02-03 1 724
2025-05-15 0 724
2025-06-18 0 724
2025-12-20 0 724
groupby("customer").tail(1) takes each customer's last row, and a normal merge copies that one value onto every event. Four events, four dates, one balance, and every one of those values comes from after its event. No error and no warning. It runs fine, and that's the problem.
The right way: merge_asof
def join_as_of(events, history):
"""RIGHT: the balance as of each event's own time."""
return pd.merge_asof(
events.sort_values("event_time"),
history.sort_values("changed_at"),
left_on="event_time", right_on="changed_at",
by="customer", direction="backward")
right join, customer C001
event_time missed balance
2025-02-03 1 2401
2025-05-15 0 1768
2025-06-18 0 1219
2025-12-20 0 1073
Read it argument by argument:
- Both tables sorted by time.
merge_asofraises an error otherwise. left_on/right_onsay which times to compare. It looks for the closest time, not an equal one.by="customer"means only this customer's own rows can match.direction="backward"means the last row at or before the event.
The first event gets 2,401, and each later event gets its own value: the value as of that day, never one after.
Check the joined table
differ = wrong["balance"].values != right["balance"].values
print("rows that differ:", differ.sum(), "of", len(wrong))
for name, table in (("wrong", wrong), ("right", right)):
late = (table["changed_at"] > table["event_time"]).sum()
by = table.groupby("missed")["balance"].mean().round()
print(name, "from the future:", late,
"| mean paid", int(by[0]), "missed", int(by[1]))
rows that differ: 1196 of 1198
wrong from the future: 1198 | mean paid 1902 missed 392
right from the future: 0 | mean paid 2361 missed 1176
All but two rows differ. The check worth keeping is the middle one: count the rows where changed_at is after event_time. The wrong table has all of them; the right table has zero.
Now the mean balance. In the wrong table, people who paid have about 1,900 and people who missed about 400: almost five times. In the right table it's about 2,400 against 1,200: about two times. The real signal is there, but the wrong table makes it look much stronger.
One tiny model, both tables
The same logistic regression on balance and amount, trained on events before October 2025 and tested on the rest. Each model trains on its own table (tables builds both joins for one data seed, and auc scores the test events):
COLS = ["balance", "amount"]
CUT = pd.Timestamp("2025-10-01")
def fit(table):
train = table[table["event_time"] < CUT]
model = make_pipeline(StandardScaler(),
LogisticRegression(random_state=42))
return model.fit(train[COLS], train["missed"])
def score_once(seed, hit=HIT, log=False):
wrong, right = tables(seed, hit, log)
wrong_model, right_model = fit(wrong), fit(right)
return (auc(wrong_model, wrong), # the score it reports
auc(right_model, right), # the honest score
auc(wrong_model, right)) # wrong model, as-of values
wrong table, its own score 0.808
right table, its own score 0.772
wrong model, as-of values 0.785
The wrong table reports an AUC of 0.808, the right one 0.772. But on the real day nobody has the balance from later, so the third line gives the wrong model the as-of values it would really get: 0.785. The top score is a promise it can't keep.
One seed proves nothing, so twenty
wrong right served
mean of 20 0.782 0.727 0.744
lowest 0.747 0.668 0.690
highest 0.827 0.777 0.794
wrong beat right 20 of 20
wrong beat served 20 of 20
served beat right 18 of 20
log balance 0.779 0.760 0.755
log: served beat right 10 of 20
hit 0.25 0.710 0.712 0.712
hit 0.1 0.672 0.708 0.690
- The wrong table came out higher than the right one in all 20 data sets.
- Given as-of values, the wrong model fell below its own score in all 20.
- To be fair, the wrong model served as-of values still averages a bit above the honest model (0.744 against 0.727). Take the log of the balance, and the two come out about level (better in 10 of 20).
- The size of this gap is our doing, because we chose the halving. If a miss takes a quarter, the tables tie. If it takes a tenth, the wrong table actually scores lower.
So a wrong join doesn't always flatter you. It just doesn't measure the real day.
Common mistakes
- Joining the latest value (a plain
mergeon a "current" table) onto historical events. - Forgetting
by=inmerge_asof, so one customer picks up another customer's row. - Unsorted inputs.
merge_asofneeds both sides sorted on the time keys. - Using the time something happened instead of the time your system knew it.
changed_atshould be when the value became available. Late-arriving data gives you the same bug. - Trusting the score to tell you. Count rows from the future instead.
Quick recap
| Wrong join | merge_asof | |
|---|---|---|
| C001 on 3 Feb | 724 (today) | 2,401 (as of the event) |
| Rows from the future | 1,198 of 1,198 | 0 |
| Mean balance, paid vs missed | 1,902 vs 392 | 2,361 vs 1,176 |
| AUC, seed 42 | 0.808 reported, 0.785 served | 0.772 |
Try it yourself
In make_data.py, set HIT = 0.1 and run score.py. Which table scores higher now, and why?
The project and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
Next →Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.