Friday, December 27, 2024
Google search engine
HomeLanguagespandas.merge_asof() function in Python

pandas.merge_asof() function in Python

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:

RELATED ARTICLES

Most Popular

Recent Comments