w3resource

Pandas: Data Manipulation - merge_asof() function

merge_asof() function

Perform an asof merge. This is similar to a left-join except that we match on nearest key rather than equal keys.
Both DataFrames must be sorted by the key.
For each row in the left DataFrame:

  • A “backward” search selects the last row in the right DataFrame whose 'on' key is less than or equal to the left’s key.
  • A “forward” search selects the first row in the right DataFrame whose 'on' key is greater than or equal to the left’s key.
  • A “nearest” search selects the row in the right DataFrame whose 'on' key is closest in absolute distance to the left’s key.

The default is “backward” and is compatible in versions below 0.20.0. The direction parameter was added in version 0.20.0 and introduces “forward” and “nearest”.

Optionally match on equivalent keys with 'by' before searching with 'on'.

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:

Name Description Type Required / Optional
left DataFrame Required
right DataFrame Required
on Field name to join on. Must be found in both DataFrames. The data MUST be ordered. Furthermore this must be a numeric column, such as datetimelike, integer, or float. On or left_on/right_on must be given. label Required
left_on Field name to join on in left DataFrame. label Optional
right_on Field name to join on in right DataFrame. label Optional
left_index Use the index of the left DataFrame as the join key. boolean Optional
right_index Use the index of the right DataFrame as the join key. boolean Optional
by Match on these columns before performing merge operation. column name or list of column names Optional
left_by Field names to match on in the left DataFrame. column name Optional
right_by Field names to match on in the right DataFrame. column name Optional
suffixes Suffix to apply to overlapping column names in the left and right side, respectively. 2-length sequence (tuple, list, …) Optional
tolerance Select asof tolerance within this range; must be compatible with the merge index. integer or Timedelta, default None Optional
allow_exact_matches
  • If True, allow matching with the same ‘on’ value (i.e. less-than-or-equal-to / greater-than-or-equal-to)
  • If False, don’t match the same ‘on’ value (i.e., strictly less-than / strictly greater-than)
boolean, default True Optional
direction Whether to search for prior, subsequent, or closest matches. {'backward' (default), 'forward', or 'nearest'} Optional

Returns: merged: DataFrame.

Example:


Download the Pandas DataFrame Notebooks from here.

Previous: merge_ordered() function
Next: concat() function



Follow us on Facebook and Twitter for latest update.