Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Pandas · Function

pd.merge_asof

Merges ordered DataFrames by key distance rather than exact equality, retaining every left row. It supports backward, forward, and nearest matching, optional tolerances, and group-wise matching.

Since
0.20.0

How it works

Use this function for an ordered left-style merge when keys do not match exactly. It searches the right frame for a prior, subsequent, or closest key, optionally within groups, while retaining every left row; both inputs must be sorted ascending by the merge key.

Syntax

pandas.merge_asof(left, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, by=None, left_by=None, right_by=None, suffixes=('_x', '_y'), tolerance=None, allow_exact_matches=True, direction='backward')

Parameters

NameTypeDescription
leftDataFrameLeft DataFrame.
rightDataFrameRight DataFrame.
onlabelColumn name present in both DataFrames and used as the merge key; alternatively use left_on and right_on.
left_onlabel or list-likeColumn or index level in the left DataFrame used as the merge key.
right_onlabel or list-likeColumn or index level in the right DataFrame used as the merge key.
left_indexboolUse the left DataFrame index as the merge key.
right_indexboolUse the right DataFrame index as the merge key.
bycolumn name or list of column namesColumn name or list of names matched before the distance search.
left_bycolumn name or list of column namesLeft-side grouping column or columns.
right_bycolumn name or list of column namesRight-side grouping column or columns.
suffixes2-length sequenceSuffixes appended to overlapping column names.
toleranceint or timedelta, optionalMaximum permitted distance between keys; defaults to no limit.

Returns

DataFrame. A DataFrame of the two merged objects, containing all rows from the left DataFrame and the nearest matches from the right DataFrame.

Key points

  • The function joins rows according to distance between merge keys instead of requiring equal keys.
  • Every left row participates like a left join, with the right row chosen by proximity.
  • The default backward mode attaches the latest right-side key at or before each left key.
  • Forward mode attaches the earliest right-side key at or after each left key.
  • Nearest mode chooses the right row with the smallest absolute key difference.
  • Use by, left_by, or right_by to constrain candidate matches to equal grouping keys before distance matching.

Common mistakes

  • Sort both inputs by the merge key in ascending order before calling the function; sorting grouping columns is not required.
  • Unordered merge keys violate the function's requirement and can produce an error or invalid result.
  • When using a named merge key, that key must exist in both DataFrames.
  • With allow_exact_matches=False, backward and forward searches exclude equal keys.

Example: Attach the latest prior quote

import pandas as pd

quotes = pd.DataFrame({
    "time": pd.to_datetime(["2024-01-01 09:00", "2024-01-01 09:05"]),
    "price": [100, 101],
})
trades = pd.DataFrame({
    "time": pd.to_datetime(["2024-01-01 09:02", "2024-01-01 09:07"]),
    "quantity": [10, 5],
})

result = pd.merge_asof(
    trades.sort_values("time"),
    quotes.sort_values("time"),
    on="time",
    direction="backward",
)
print(result)

For each trade, attach the latest quote at or before its timestamp.

When to use it

Time-aligned event enrichment

Attach the most recent quote, sensor reading, or status to each event timestamp.

Forward temporal lookup

Find the next scheduled event after each observation.

Nearest matching with tolerance

Associate observations with the closest measurement within a bounded time or numeric gap.

Grouped as-of joins

Match records within independent instruments, products, or entities before comparing ordered keys.

Interview questions

QWhat problem does pandas.merge_asof solve?

It performs a merge by key distance rather than equality. It keeps all rows from the left frame and selects a matching right row according to direction.

Follow-up: How would you implement a nearest-event lookup? Use direction='nearest', and add tolerance when matches must fall within a maximum distance.

QHow do the direction options differ?

The default backward search chooses the last right-side key less than or equal to the left key. Forward chooses the first key greater than or equal to it, while nearest minimizes absolute distance.

Follow-up: What happens when an exact match is disallowed? Set allow_exact_matches=False so backward and forward searches use strict inequalities.

QWhat prerequisites and grouping options does the function have?

The left and right merge keys must be sorted ascending before the call. A by column or list can restrict matching to equivalent groups before the distance search.

Follow-up: Is sorting by by required? No: the documentation says sorting additional by grouping columns is not required.

  • pandas.merge
  • pandas.merge_ordered
  • DataFrame.merge

Source: pandas.merge_asof — pandas 3.0.6 documentation - PyData. Checked 2026-10-15.