---
title: Point-in-time (as-of) feature join
url: https://gurkanozkan.ai/learn/coding/mle-point-in-time-as-of-feature-join-03/
markdown: https://gurkanozkan.ai/learn/coding/mle-point-in-time-as-of-feature-join-03.md
kind: coding
difficulty: Medium
topics:
  - Feature store
  - Leakage
  - Binary search
json: https://gurkanozkan.ai/api/learn/coding/mle-point-in-time-as-of-feature-join-03.json
robots: noindex
---

# Point-in-time (as-of) feature join

`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

```python
def asof_join(labels: list[tuple[str, int]], features: list[tuple[str, int, object]]) -> list[object]: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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]
True
```

## Hints

1. Per entity, sort features by time.
2. Binary-search the sorted timestamps (bisect_left) for each label_ts.
3. Take the row just before the insertion point — the largest feature_ts strictly below the label.

## Reference solution

```python
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 out
```

## What 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_asof` and the available-at vs event-time distinction.

## Common mistakes

- using `<=` (lets same-timestamp information leak)
- a linear scan per label.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
