Sub topic 5
The As-of Join: Latest Value at or Before the Prediction Time
Assume you know basic supervised learning, pandas DataFrames, SQL joins, window functions, and timestamps with time zones. This chapter focuses on one question: which feature value was actually available when a prediction was made?
An as-of join matches each label row with the latest feature row whose timestamp is at or before the label's prediction time. It prevents a training row from using information from the future.
Why an ordinary join leaks information
Suppose a model predicts whether a customer will churn at 2026-01-10 12:00. The customer's feature history contains these values:
| customer_id | feature_ts | avg_spend_30d |
|---|---|---|
| C17 | 2026-01-08 09:00 | 42.00 |
| C17 | 2026-01-12 09:00 | 18.00 |
A join that selects the customer's latest value uses 18.00. That value was created two days after the prediction. The training row therefore contains future information.
The correct match is 42.00. The join must consider both the customer and time.
The pandas as-of join
pandas.merge_asof performs this lookup. Sort both inputs by their timestamp columns first. With direction="backward", pandas selects the most recent right-side row that is no later than the left-side row.
import pandas as pd
labels = pd.DataFrame({
"customer_id": ["C17", "C17"],
"prediction_ts": pd.to_datetime([
"2026-01-10 12:00",
"2026-01-15 12:00",
]),
"churned": [0, 1],
})
features = pd.DataFrame({
"customer_id": ["C17", "C17", "C17"],
"feature_ts": pd.to_datetime([
"2026-01-08 09:00",
"2026-01-12 09:00",
"2026-01-14 09:00",
]),
"avg_spend_30d": [42.0, 18.0, 16.0],
})
labels = labels.sort_values("prediction_ts")
features = features.sort_values("feature_ts")
train = pd.merge_asof(
labels,
features,
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta("30D"),
)
print(train[["customer_id", "prediction_ts", "avg_spend_30d"]])The first label receives 42.0. The second receives 16.0. A feature row after a prediction cannot match it.
by="customer_id" keeps customers separate. Without it, a feature from one customer could be attached to another customer's label.
The SQL version
In SQL, first keep candidate feature rows that satisfy the time condition. Then use ROW_NUMBER to retain the newest candidate for each label.
WITH candidates AS (
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
f.avg_spend_30d,
f.event_ts AS feature_ts,
ROW_NUMBER() OVER (
PARTITION BY l.customer_id, l.prediction_ts
ORDER BY f.event_ts DESC
) AS rn
FROM labels AS l
LEFT JOIN feature_history AS f
ON f.customer_id = l.customer_id
AND f.event_ts <= l.prediction_ts
)
SELECT
customer_id,
prediction_ts,
churned,
avg_spend_30d,
feature_ts
FROM candidates
WHERE rn = 1;The LEFT JOIN preserves labels with no usable feature. Their feature columns become NULL, which lets you measure missingness instead of silently dropping predictions.
Common errors
- Joining to a table that stores only the current feature value. Historical values are required for historical predictions.
- Using
<when a value recorded exactly at prediction time should be available, or using<=when that value was not available until afterward. Choose the operator from the system's time semantics. - Forgetting duplicate label keys. If two rows share the same customer and prediction time, define whether they represent separate examples.
- Sorting incorrectly before
merge_asof. Sort by the timestamp used for the join, and verify the library's requirements for grouped joins. - Accepting a stale value without checking its age. A technically valid old value may not represent the state needed for the prediction.
Exercise
A label for customer C9 has prediction_ts 2026-03-10 10:00. Feature rows exist at 2026-03-08 10:00 and 2026-03-10 10:05. Which row should an as-of join select?
Show answer
The 2026-03-08 10:00 row. The later row is newer than the prediction time and is future information.