Point-in-time (as-of) feature join
Problem
labels is a list of (entity, label_ts). features is a list of (entity, feature_ts, value) in any order, with unique (entity, feature_ts). For each label, return the value of the same entity’s feature row with the largest feature_ts strictly less than label_ts, or None if there is none. Output follows the order of labels.
Signature
def asof_join(labels: list[tuple[str, int]], features: list[tuple[str, int, object]]) -> list[object]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> asof_join([('u',10)], [('u',5,1.0),('u',9,2.0),('u',12,3.0)]) == [2.0]
True
>>> asof_join([('u',9)], [('u',5,1.0),('u',9,2.0)]) == [1.0]
TrueHints
Per entity, sort features by time.
Binary-search the sorted timestamps (bisect_left) for each label_ts.
Take the row just before the insertion point — the largest feature_ts strictly below the label.
Reference solution
from collections import defaultdict
import bisect
def asof_join(labels, features):
by_ent = defaultdict(list)
for e, t, v in features:
by_ent[e].append((t, v))
for e in by_ent:
by_ent[e].sort(key=lambda p: p[0])
keys = {e: [t for t, _ in lst] for e, lst in by_ent.items()}
out = []
for e, t in labels:
if e not in by_ent:
out.append(None)
continue
i = bisect.bisect_left(keys[e], t) - 1 # strictly earlier
out.append(by_ent[e][i][1] if i >= 0 else None)
return outWhat a strong solution covers
- Groups features per entity, sorts by time, then binary search (
bisect_left), for O((F + L) log F). - Explains why the strict inequality prevents leakage.
- Mentions pandas
merge_asofand the available-at vs event-time distinction.
Common mistakes
- using
<=(lets same-timestamp information leak) - a linear scan per label.