merge_asof()
merge_asof joins on the nearest key rather than an exact match, ideal for time series.
In this page:
Syntax
merged = pd.merge_asof(left, right, on="sorted_column")
merge_asof()
pd.merge_asof matches each row in the left table to the last right-hand row whose key is less than or equal to it. Both tables must be sorted by the key. Use direction to pick backward, forward or nearest, and by to match groups.
Note:
A typical use is attaching the latest price quote to each trade.
Example: merge_asof()
import pandas as pd
trades = pd.DataFrame({"time": pd.to_datetime(["10:00:05", "10:00:15"]), "qty": [100, 200]})
quotes = pd.DataFrame({"time": pd.to_datetime(["10:00:00", "10:00:10", "10:00:20"]), "price": [50.0, 51.0, 52.0]})
print(pd.merge_asof(trades, quotes, on="time"))
# Output:
# time qty price
# 0 2026-09-20 10:00:05 100 50.0
# 1 2026-09-20 10:00:15 200 51.0
Related Topics
Common Mistakes
- Not sorting by the key first
- Using it for exact-match joins
- Forgetting tolerance for stale matches
Chapter Summary
- Matches on the nearest key
- Inputs must be sorted
- direction picks the search side
- by matches groups first
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: