📜  Python中的 pandas.merge_asof()函数

📅  最后修改于: 2022-05-13 01:54:54.146000             🧑  作者: Mango

Python中的 pandas.merge_asof()函数

此方法用于执行 asof 合并。这类似于左连接,除了我们匹配最近的键而不是相等的键。两个 DataFrame 都必须按 key 排序。

以下是上述方法的实现以及一些示例:

示例 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))


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'))


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))


输出:

示例 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'))

输出 :

示例 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))

输出: