Sub topic 14
Matching nearest earlier records with join_asof
This chapter assumes you know join with on keys, null values after a left join, and how to sort a DataFrame. An as-of join is for ordered keys such as timestamps, where an exact match rarely exists.
What an as-of join does
A regular join needs equal keys. An as-of join matches each left row to the closest right row by key value. By default it picks the last right row whose key is less than or equal to the left key. Polars calls this the backward strategy.
A typical case is attaching the latest price quote to each trade. The quote and the trade almost never share the same timestamp.
A basic example
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 10Every left row is kept, as in a left join. A left row with no earlier right row gets null, which is what happens at time 1.
Strategy, tolerance, and groups
Three parameters cover most real cases:
| Parameter | Effect |
|---|---|
| `strategy` | `"backward"` (default) takes the last key at or before. `"forward"` takes the first key at or after. `"nearest"` takes the closest key in either direction. |
| `tolerance` | The largest allowed key distance. Matches farther away become null. |
| `by` | Columns that must match exactly. The as-of search runs separately inside each group. |
The next example matches quotes per symbol and ignores quotes more than 3 time units old:
trades = pl.DataFrame({
"time": [1, 5, 10, 11],
"sym": ["A", "B", "A", "B"],
"qty": [100, 200, 300, 400],
})
quotes = pl.DataFrame({
"time": [2, 6, 8],
"sym": ["A", "B", "A"],
"price": [9.5, 9.8, 9.9],
})
out = trades.join_asof(quotes, on="time", by="sym", tolerance=3)
print(out) # prices: null, null, 9.9, nullEach row follows from the rules above:
- Trade
(1, A): symbol A has no quote at or before time 1, so the price is null. - Trade
(5, B): B's only quote is at time 6, which is later, so the price is null. - Trade
(10, A): the latest A quote is at time 8, within the tolerance, so the price is 9.9. - Trade
(11, B): the B quote at time 6 is 5 units old, which exceeds the tolerance of 3, so the price is null.
For datetime keys, give tolerance as a string such as "2m" or a timedelta. For integer keys, use an integer.
Common errors
- Unsorted keys. Sort both tables on the key before joining. With
by, each group must be sorted. - Mismatched key types. The key columns must have the same dtype. Casting an integer key to
Int64on both sides is a common fix. - Expecting a many-to-many result. Each left row gets at most one right row. If several right rows tie, you still get one match.
- Different key names. Use
left_onandright_oninstead ofon. Overlapping non-key column names get the_rightsuffix, as in a regular join.
Exercise
Using the first trades and quotes tables (trades at times 1, 5 and 10, quotes at times 2 and 6), which strategy would give the trade at time 1 a non-null price, and what would that price be?
Show answer
strategy="forward". It takes the first quote at or after each trade time, so the trade at time 1 gets the quote at time 2, with price 9.5. The trade at time 10 would then get null, because no quote exists at or after time 10.