Python中的 pandas.merge_asof()函数
此方法用于执行 asof 合并。这类似于左连接,除了我们匹配最近的键而不是相等的键。两个 DataFrame 都必须按 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.
以下是上述方法的实现以及一些示例:
示例 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))
输出: