Sub topic 14
Matching nearest earlier records with join_asof
This chapter assumes you know how join works (left and inner joins, on, how), and that you can build a DataFrame and write expressions with pl.col. It also assumes you have seen group_by_dynamic for time-ordered data. Examples use a recent Polars release.
Why an equality join is not enough
A normal join matches rows when the key values are equal. Ordered data often has no equal keys. Suppose you have a table of trades and a table of price quotes. A trade at time 5 rarely lines up with a quote at exactly time 5. What you want is the most recent quote at or before the trade.
join_asof solves this. For each row in the left table, it looks in the right table for the row whose key is closest to the left key, in a direction you choose. It then attaches that row's columns.
The default: backward matching
import polars as pl
trades = pl.DataFrame({"time": [1, 5, 10], "qty": [100, 200, 300]})
quotes = pl.DataFrame({"time": [2, 6], "price": [9.5, 9.8]})
out = trades.join_asof(quotes, on="time")
print(out) # price: null for time 1, 9.5 for time 5, 9.8 for time 10The default strategy is "backward". For each trade, Polars picks the right row with the largest key that is less than or equal to the trade's key.
- Time 1: no quote at or before time 1 exists, so
priceis null. - Time 5: the latest quote at or before 5 is the one at time 2, so the price is 9.5.
- Time 10: the latest quote is the one at time 6, so the price is 9.8.
The join keeps every left row, like a left join. Rows with no match get nulls. The result always has the same number of rows as the left table, because each left row matches at most one right row.
The diagram shows how one left row is resolved.
Sorting is required
join_asof finds matches with a sorted search, not a hash lookup. Both tables must be sorted ascending on the key column. If they are not, the result is wrong, and Polars may warn or raise an error depending on the version.
The key columns must also have the same data type. Joining an integer key to a float key, or a Datetime in microseconds to one in nanoseconds, fails or behaves unexpectedly. Cast one side first.
Choosing a strategy
The strategy parameter controls the search direction.
| Strategy | Matches | Typical use |
|---|---|---|
| `"backward"` (default) | Last right key less than or equal to the left key | Latest known value, such as the current price |
| `"forward"` | First right key greater than or equal to the left key | Next event after a row, such as the next delivery |
| `"nearest"` | Closest right key on either side | Aligning two sensors sampled at different times |
Using the same tables as before:
backward = trades.join_asof(quotes, on="time", strategy="backward")
forward = trades.join_asof(quotes, on="time", strategy="forward")
nearest = trades.join_asof(quotes, on="time", strategy="nearest")
print(backward) # price: null, 9.5, 9.8
print(forward) # price: 9.5, 9.8, null
print(nearest) # price: 9.5, 9.8, 9.8For nearest at time 5, the quote at time 6 is 1 unit away and the quote at time 2 is 3 units away, so time 6 wins. At time 10 only the time-6 quote is closer than nothing, so it is used.
Exact matches count as matches for backward and forward. If you want strictly earlier rows only, pass allow_exact_matches=False. A trade at time 6 would then skip a quote at time 6 and use the one before it.
Matching within groups with by
Real data usually mixes entities. A quote for ticker A should never attach to a trade in ticker B. The by parameter restricts matching to rows that have equal values in the given column or columns. The on key is still the sorted one.
Limiting staleness with tolerance
A backward match may find a quote from an hour ago. The tolerance parameter sets the largest allowed distance between the left key and the matched right key. If the best candidate is farther away, the result is null instead.
For integer keys, the tolerance is a number. For datetime keys, it is a timedelta or a duration string such as "3s" or "2m".
from datetime import datetime
trades = pl.DataFrame({
"time": [
datetime(2026, 1, 1, 9, 0, 1),
datetime(2026, 1, 1, 9, 0, 6),
datetime(2026, 1, 1, 9, 0, 9),
datetime(2026, 1, 1, 9, 0, 12),
],
"ticker": ["A", "B", "A", "B"],
"qty": [100, 200, 300, 400],
})
quotes = pl.DataFrame({
"time": [
datetime(2026, 1, 1, 9, 0, 0),
datetime(2026, 1, 1, 9, 0, 2),
datetime(2026, 1, 1, 9, 0, 4),
datetime(2026, 1, 1, 9, 0, 8),
],
"ticker": ["A", "B", "A", "A"],
"price": [10.0, 20.0, 10.5, 11.0],
})
out = trades.join_asof(quotes, on="time", by="ticker", tolerance="3s")
print(out) # price: 10.0, null, 11.0, nullWalk through each trade:
- Ticker A at 09:00:01. The latest A quote is at 09:00:00, 1 second earlier, so the price is 10.0.
- Ticker B at 09:00:06. The only B quote is at 09:00:02, 4 seconds earlier. That exceeds 3 seconds, so the price is null.
- Ticker A at 09:00:09. The latest A quote is at 09:00:08, so the price is 11.0.
- Ticker B at 09:00:12. The B quote is 10 seconds old, so the price is null.
Without by, trade 2 would have matched the A quote at 09:00:04, which is the wrong ticker. Without tolerance, trades 2 and 4 would carry stale B prices.
Column names, keys, and nulls
- Different key names. Use
left_onandright_oninstead ofon. The right key column is dropped from the output when the names differ, as in a regular join. - Overlapping columns. If both tables have a non-key column with the same name, the right one is renamed with the
suffixargument, which defaults to"_right". - Null keys. Nulls in the key column cannot be ordered meaningfully. Drop or fill them before the join.
- Duplicate right keys. If several right rows share the same key, only one is picked. Polars does not guarantee which. Deduplicate or aggregate the right table first if the choice matters.
How it relates to other tools
join_asof joins on inexact, ordered keys. A regular join needs equal keys. group_by_dynamic aggregates many rows into fixed time buckets and reduces row count. join_asof does not aggregate. It picks one row per left row and keeps the left row count.
A common pipeline is to use join_asof to attach the latest reference value to each event, then use group_by_dynamic or over to summarize the result.
join_asof is also available on LazyFrame with the same arguments. In lazy mode, Polars can push projections down and skip reading columns you do not use. The sort requirement still applies, so sort inside the lazy query before the join.
Exercise
Given trades with time [3, 7, 12] and quotes with time [1, 7, 10] and price [1.0, 2.0, 3.0], what prices does trades.join_asof(quotes, on="time") return? What changes if you add allow_exact_matches=False?
Show answer
The default backward strategy returns 1.0, 2.0, 3.0. Time 3 matches the quote at 1, time 7 matches the quote at 7 because exact matches are allowed, and time 12 matches the quote at 10. With allow_exact_matches=False, the trade at time 7 can no longer use the quote at 7, so it falls back to the quote at 1. The prices become 1.0, 1.0, 3.0.
Exercise
A join_asof with by="ticker" returns a null price for a trade even though a quote for that ticker exists much earlier. Name two possible causes.
Show answer
A tolerance is set and the earlier quote is farther away than the tolerance allows. Or the quote's key is later than the trade's key, so the default backward strategy cannot match it. A third cause is a data type or value mismatch in the by column, such as different casing, so no group matches.