在 Pandas 里,merge
函数是一个非常强大且常用的工具,它用于将两个或多个 DataFrame
按照指定的条件进行合并。这类似于 SQL 中的 JOIN
操作。下面详细介绍 merge
函数的用法:
基本语法
python
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)
参数说明
left
:参与合并的左侧DataFrame
。right
:参与合并的右侧DataFrame
。how
:合并方式,可选值有'inner'
(内连接,默认值)、'outer'
(外连接)、'left'
(左连接)、'right'
(右连接)。on
:用于连接的列名,该列必须同时存在于左右两个DataFrame
中。如果未指定,则会自动以重叠列名作为连接键。left_on
:左侧DataFrame
中用作连接键的列。right_on
:右侧DataFrame
中用作连接键的列。left_index
:如果为True
,则使用左侧DataFrame
的索引作为连接键。right_index
:如果为True
,则使用右侧DataFrame
的索引作为连接键。sort
:根据连接键对合并后的数据进行排序,默认为False
。suffixes
:当左右DataFrame
存在除连接键外的重叠列名时,用于追加到重叠列名后的后缀,默认为('_x', '_y')
。copy
:是否复制数据,默认为True
。indicator
:添加一个名为_merge
的列,显示每一行的合并来源,值为'left_only'
、'right_only'
或'both'
,默认为False
。validate
:检查合并类型是否有效,例如'one_to_one'
、'one_to_many'
等。
合并方式示例
1. 内连接(how='inner'
)
内连接只保留两个 DataFrame
中连接键匹配的行。
python
import pandas as pd
# 创建示例 DataFrame
left = pd.DataFrame({
'key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']
})
right = pd.DataFrame({
'key': ['K0', 'K1', 'K4', 'K5'],
'C': ['C0', 'C1', 'C4', 'C5'],
'D': ['D0', 'D1', 'D4', 'D5']
})
# 内连接
result = pd.merge(left, right, on='key', how='inner')
print(result)
在这个例子中,只有 key
列值为 'K0'
和 'K1'
的行被保留,因为只有这些行在两个 DataFrame
中都存在。
2. 外连接(how='outer'
)
外连接会保留两个 DataFrame
中所有的行,不匹配的部分用 NaN
填充。
python
# 外连接
result = pd.merge(left, right, on='key', how='outer')
print(result)
这里会包含 left
和 right
中所有的行,对于没有匹配的行,对应列的值会显示为 NaN
。
3. 左连接(how='left'
)
左连接会保留左侧 DataFrame
中的所有行,右侧 DataFrame
中不匹配的部分用 NaN
填充。
python
# 左连接
result = pd.merge(left, right, on='key', how='left')
print(result)
无论右侧 DataFrame
中是否有匹配项,左侧 DataFrame
的所有行都会被保留。
4. 右连接(how='right'
)
右连接会保留右侧 DataFrame
中的所有行,左侧 DataFrame
中不匹配的部分用 NaN
填充。
python
# 右连接
result = pd.merge(left, right, on='key', how='right')
print(result)
与左连接相反,这里会保证右侧 DataFrame
的所有行都被保留。
使用不同列名作为连接键
如果左右 DataFrame
中用于连接的列名不同,可以使用 left_on
和 right_on
参数。
python
left = pd.DataFrame({
'key_left': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']
})
right = pd.DataFrame({
'key_right': ['K0', 'K1', 'K4', 'K5'],
'C': ['C0', 'C1', 'C4', 'C5'],
'D': ['D0', 'D1', 'D4', 'D5']
})
result = pd.merge(left, right, left_on='key_left', right_on='key_right', how='inner')
print(result)
在这个例子中,left
的 key_left
列和 right
的 key_right
列被用作连接键。
使用索引作为连接键
可以通过设置 left_index
和 right_index
参数为 True
,使用索引作为连接键。
python
left = pd.DataFrame({
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']
}, index=['K0', 'K1', 'K2', 'K3'])
right = pd.DataFrame({
'C': ['C0', 'C1', 'C4', 'C5'],
'D': ['D0', 'D1', 'D4', 'D5']
}, index=['K0', 'K1', 'K4', 'K5'])
result = pd.merge(left, right, left_index=True, right_index=True, how='inner')
print(result)
这里使用了两个 DataFrame
的索引进行连接。
通过灵活运用 merge
函数的各种参数,可以满足不同场景下的 DataFrame
合并需求。