Sub topic 12
Matching nearest keys with merge_asof
This chapter assumes you can run merge with on, how, and suffixes, and that you know the datetime64 dtype and pd.to_datetime. You also need to know how to sort a DataFrame with sort_values.
Why exact matching is not enough
A regular merge matches keys that are equal. That works for customer IDs, but it fails for measurements taken at different moments. A trade executes at 09:00:01, and the quotes were published at 09:00:00 and 09:00:03. No timestamps are equal, so an inner merge returns nothing, and a left merge returns only NaN for the quote columns.
pd.merge_asof solves this. For each row in the left table it finds one row in the right table whose key is closest in a direction you choose, and it attaches that row's columns. The name comes from "as-of" lookups: "what was the latest quote as of this trade?"
Typical uses:
- Attaching the most recent price, quote, or exchange rate to each event.
- Attaching the latest sensor reading to each log entry.
- Finding which pricing rule or policy was in effect on a given date.
The working model
merge_asof behaves like a left join with a different matching rule. These properties follow from that.
- Every left row is kept, in its original order. Unmatched rows get
NaNin the right columns. - Each left row matches at most one right row. The output has exactly as many rows as the left table. Duplicate right rows cannot multiply rows the way they do in a normal merge.
- A right row can be reused. Two trades between the same two quotes both receive the same quote.
- Both inputs must be sorted ascending by the
onkey. The function relies on this order to search efficiently. It does not sort for you. - The
onkey must be ordered and numeric-like. Datetimes are the usual case, but integers and floats also work.
A first as-of merge
This block builds the tables used by the following examples.
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:
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 first trade at 09:00:01 gets the 09:00:00 quote. The second trade at 09:00:05 gets the 09:00:03 quote. The 09:00:06 quote is never used, because by default the search only looks backward.
Choosing a direction
The direction argument sets which side of the left key to search.
| Value | Matches | Use when |
|---|---|---|
| `"backward"` (default) | Last right key less than or equal to the left key | You want the latest known value as of an event |
| `"forward"` | First right key greater than or equal to the left key | You want the next value after an event |
| `"nearest"` | Closest right key on either side | Timestamps are approximate and either side is acceptable |
for direction in ["backward", "forward", "nearest"]:
out = pd.merge_asof(
trades, quotes, on="time", by="ticker", direction=direction
)
print(direction, out["bid"].tolist())This prints backward [100.0, 100.5], forward [100.5, 101.0], and nearest [100.0, 101.0]. For the 09:00:05 trade, the 09:00:03 quote is 2 seconds away and the 09:00:06 quote is 1 second away, so nearest picks the later one.
The default backward is the safe choice for most analysis. Using forward or nearest lets a row see information from its future. In a model or backtest that is data leakage.
Limiting how stale a match can be
By default a trade is matched to a quote even if the quote is an hour old. The tolerance argument sets the maximum allowed distance. If no right key falls within it, the right columns are NaN.
print(
pd.merge_asof(
trades, quotes, on="time", by="ticker",
tolerance=pd.Timedelta("1500ms"),
)
)The first trade is 1 second from its quote and keeps bid 100.0. The second trade is 2 seconds from its quote, which exceeds 1.5 seconds, so its bid becomes NaN.
The tolerance type must fit the key. Use a pd.Timedelta for datetime keys and a plain number for numeric keys. Choose a value that reflects how old data may be before it stops being meaningful.
Exact matches
allow_exact_matches=True is the default. A left row whose key equals a right key matches that right row. Set it to False to skip equal keys. This is useful when the right-hand event happens at the same instant as the left-hand event and you don't want to count it.
same_time = pd.DataFrame({
"time": pd.to_datetime(["2026-01-01 09:00:03", "2026-01-01 09:00:06"]),
"ticker": ["A", "A"],
"qty": [5, 7],
})
default = pd.merge_asof(same_time, quotes, on="time", by="ticker")
strict = pd.merge_asof(
same_time, quotes, on="time", by="ticker", allow_exact_matches=False
)
print(default["bid"].tolist())
print(strict["bid"].tolist())The default result is [100.5, 101.0]. The strict result is [100.0, 100.5], because each equal timestamp is skipped and the previous quote is used.
Matching within groups with by
In the examples above, by="ticker" restricts matching to rows with the same ticker. Without by, a trade in ticker B could receive a quote for ticker A just because it was closest in time.
trades2 = pd.DataFrame({
"time": pd.to_datetime(["2026-01-01 09:00:02", "2026-01-01 09:00:04"]),
"ticker": ["A", "B"],
"qty": [1, 2],
})
quotes2 = pd.DataFrame({
"time": pd.to_datetime(["2026-01-01 09:00:01", "2026-01-01 09:00:03"]),
"ticker": ["A", "B"],
"bid": [50.0, 80.0],
})
print(pd.merge_asof(trades2, quotes2, on="time", by="ticker"))
print(pd.merge_asof(trades2, quotes2, on="time"))The first call gives bid values 50.0 and 80.0. The second call has no by, so ticker B's trade at 09:00:04 matches the latest quote overall, which is B's here. Ticker A's trade at 09:00:02 would match A's quote at 09:00:01 in this small case, so the two outputs look the same. With more rows interleaved, the second call would mix tickers. The second call would also suffix the shared ticker column as ticker_x and ticker_y.
by accepts a list for several grouping columns. The by columns match exactly, and only on is matched approximately.
Sorting and other errors
The most common failure is unsorted input.
shuffled = quotes.sample(frac=1, random_state=0)
try:
pd.merge_asof(trades, shuffled, on="time", by="ticker")
except ValueError as err:
print("Failed:", err)pandas raises ValueError with a message saying the right keys must be sorted. Fix it with sort_values("time") on the offending table. You only need to sort by on. The by columns do not need to be sorted.
Other errors you will meet:
- Null keys. A
NaTorNaNin theoncolumn raises aValueErrorabout null values. Drop or fill those rows first. - Mismatched key dtypes. An
int64key on one side anddatetime64on the other raisesMergeError. Convert both sides to the same type first, for example withpd.to_datetime. Time zones must also agree: a tz-aware column cannot be matched with a tz-naive one. - Wrong tolerance type. Passing an integer tolerance with datetime keys raises an error. Use a
Timedelta. - Overlapping column names. Non-key columns with the same name get
_xand_ysuffixes. Passsuffixes=as in a regular merge.
When the key columns have different names, use left_on and right_on. left_index=True and right_index=True let a sorted datetime index serve as the key.
Deciding between merge_asof and alternatives
| Situation | Use |
|---|---|
| Keys are identifiers and must be equal | `merge` |
| Keys are times or numbers and the latest earlier value is wanted | `merge_asof` |
| You need every pairing in a range, not one match | `merge` on a bucketed key, or a cross join then filter |
| The right table is small and keys fall into fixed intervals | Bin keys with `pd.cut`, then `merge` |
Because merge_asof returns only one match per left row, it cannot answer "all quotes within five seconds of each trade". That needs a different approach, such as a cross join per group with a filter on time difference.
Performance is rarely a concern. After the sorting step, the algorithm is a single pass over both tables. Sorting is the expensive part, so sort once and reuse the sorted tables if you run many as-of merges.
Practice
Exercise
A table readings has columns time and temp and is sorted by time. A table events has columns time and event_id and is sorted by time. You want each event to receive the latest reading taken before or at the event, but only if that reading is at most 10 minutes old, and events with a stale reading should show NaN. Write the call.
Show answer
pd.merge_asof(events, readings, on="time", direction="backward", tolerance=pd.Timedelta("10min")). The direction can be omitted because "backward" is the default. The result keeps every event row, and temp is NaN where no reading falls within the previous 10 minutes.
Exercise
A colleague runs merge_asof on two tables and gets a ValueError saying the keys must be sorted, although both tables were sorted by ticker and then time. What is wrong, and how do you fix it?
Show answer
mergeasof requires each table to be sorted ascending by the on key alone, here time. Sorting by ticker first leaves the time column out of order overall. Fix it with sortvalues("time") on both tables and keep by="ticker" in the call.