Sub topic 12
Matching nearest keys with merge_asof
This chapter assumes you know merge with on and by-style key columns, how how="left" behaves, and how to build datetime columns with pd.to_datetime. You should also be comfortable reading NaN in merged output.
Why exact matching falls short
A regular merge matches keys that are equal. Many datasets have keys that are close but never equal. A trade happens at 09:00:05, and the latest price quote arrived at 09:00:03. An exact merge on time finds no match.
pd.merge_asof is a left-join-style merge that matches each left row to the nearest key in the right table, instead of requiring equality. It returns one row for each left row, at most, so it never multiplies rows the way duplicate keys do in a normal merge.
The default: most recent earlier match
By default, merge_asof uses direction="backward". For each left row, it picks the last right row whose key is less than or equal to the left key. This fits the question "what was the latest known value at this moment?"
import pandas as pd
trades = pd.DataFrame({
"time": pd.to_datetime(["2026-01-01 09:00:01", "2026-01-01 09:00:05"]),
"ticker": ["A", "A"],
"qty": [10, 20],
})
quotes = pd.DataFrame({
"time": pd.to_datetime([
"2026-01-01 09:00:00",
"2026-01-01 09:00:03",
"2026-01-01 09:00:06",
]),
"ticker": ["A", "A", "A"],
"bid": [100.0, 100.5, 101.0],
})
print(pd.merge_asof(trades, quotes, on="time", by="ticker"))The output is:
time ticker qty bid
0 2026-01-01 09:00:01 A 10 100.0
1 2026-01-01 09:00:05 A 20 100.5The trade at :01 gets the quote from :00. The trade at :05 gets the quote from :03. The quote at :06 is in the future for both trades, so it is never used.
The by="ticker" argument adds an exact condition. Rows are matched by nearest time only within the same ticker. Without by, a quote for ticker B could be matched to a trade in ticker A.
Controlling the match
Three parameters change the behavior:
| Parameter | Effect |
|---|---|
| `direction` | `"backward"` (default), `"forward"`, or `"nearest"` |
| `tolerance` | Maximum allowed key distance. Farther matches become `NaN`. |
| `allow_exact_matches` | If `False`, an equal key is not a match. The default is `True`. |
Without tolerance, a very old quote can match a new trade. In the next example, a tolerance of 1.5 seconds rejects stale matches.
import pandas as pd
trades = pd.DataFrame({
"time": pd.to_datetime(["2026-01-01 09:00:01", "2026-01-01 09:00:05"]),
"ticker": ["A", "A"],
"qty": [10, 20],
})
quotes = pd.DataFrame({
"time": pd.to_datetime([
"2026-01-01 09:00:00",
"2026-01-01 09:00:03",
"2026-01-01 09:00:06",
]),
"ticker": ["A", "A", "A"],
"bid": [100.0, 100.5, 101.0],
})
limit = pd.Timedelta("1500ms")
print(pd.merge_asof(trades, quotes, on="time", by="ticker", tolerance=limit))
print(pd.merge_asof(trades, quotes, on="time", by="ticker",
tolerance=limit, direction="nearest"))The first call gives bid values of 100.0 and NaN. The trade at :05 is 2 seconds from the :03 quote, which exceeds the tolerance. The second call uses direction="nearest". The trade at :05 is only 1 second from the :06 quote, so it gets 101.0.
Common errors
- Unsorted keys. Both inputs must be sorted by the
oncolumn. If they are not, pandas raisesValueError: left keys must be sorted. Callsort_values("time")first. - Mismatched key types. The
oncolumns must have compatible dtypes. A datetime column on one side and an object column on the other fails. Convert withpd.to_datetimefirst. - Nulls in the
oncolumn. Missing keys are not allowed. Drop or fill them before merging. - Tolerance of the wrong type. For datetime keys, use a
Timedelta. For numeric keys, use a number.
Choosing merge_asof
Use merge_asof when the keys are ordered (usually time) and an exact match is unlikely, such as joining events to the latest reference value. Use a normal merge when keys are identifiers that must be equal.
Exercise
A DataFrame orders has a sorted placed_at column, and a DataFrame rates has a sorted effective_at column with an exchange rate. You want each order to use the rate in effect when it was placed, but only if that rate is at most one day old. Which call do you write?
Show answer
pd.mergeasof(orders, rates, lefton="placedat", righton="effective_at", direction="backward", tolerance=pd.Timedelta("1D")). Backward picks the latest rate at or before the order, and the tolerance turns older rates into NaN.