← Back to Pandas Course | Chapter 8: Merging & Joining | Lesson 6 of 7

merge_asof()

merge_asof joins on the nearest key rather than an exact match, ideal for time series.

In this page:

  1. merge_asof()
Syntax
python
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()

python
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
  1. Not sorting by the key first
  2. Using it for exact-match joins
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.