Open In App

pandas.merge_asof() function in Python

Improve
Improve
Like Article
Like
Save
Share
Report

This method is used to 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.

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 :

  • left, right : DataFrame
  • on : label, Field name to join on. Must be found in both DataFrames.
  • left_on : label, Field name to join on in left DataFrame.
  • right_on : label, Field name to join on in right DataFrame.
  • left_index : boolean, Use the index of the left DataFrame as the join key.
  • right_index : boolean, Use the index of the right DataFrame as the join key.

Below is the implementation of the above method with some examples :

Example 1 :

Python3




# importing package
import pandas
  
# creating data
left = pandas.DataFrame({'a': [1, 5, 10], 
                         'left_val': ['a', 'b', 'c']})
  
right = pandas.DataFrame({'a': [1, 2, 3, 6, 7],
                          'right_val': [1, 2, 3, 6, 7]})
  
# view data
print(left)
print(right)
  
# applying merge_asof on data
print(pandas.merge_asof(left, right, on='a'))
print(pandas.merge_asof(left, right, on='a'
                        allow_exact_matches=False))


Output:

 

Example 2 :

Python3




# importing package
import pandas
  
# creating data
left = pandas.DataFrame({'a': [1, 5, 10], 
                         'left_val': ['a', 'b', 'c']})
  
right = pandas.DataFrame({'a': [1, 2, 3, 6, 7],
                          'right_val': [1, 2, 3, 6, 7]})
  
# view data
print(left)
print(right)
  
# applying merge_asof on data
print(pandas.merge_asof(left, right, on='a'
                        direction='forward'))
print(pandas.merge_asof(left, right, on='a',
                        direction='nearest'))


Output :

Example 3 :

Python3




# importing package
import pandas
  
# creating data
left = pandas.DataFrame({'left_val': ['a', 'b', 'c']}, 
                        index=[1, 5, 10])
  
right = pandas.DataFrame({'right_val': [1, 2, 3, 6, 7]}, 
                         index=[1, 2, 3, 6, 7])
  
# view data
print(left)
print(right)
  
# applying merge_asof on data
print(pandas.merge_asof(left, right, left_index=True
                        right_index=True))


Output:



Last Updated : 14 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads