Pandas pd.merge() function
pd.merge() is a function in the Pandas library used toJoin two DataFrames by columnsfunction. It is similar to the JOIN operation in SQL, and can merge two data tables into one based on one or more common columns.
This is one of the most commonly used merge methods in data analysis and processing, especially suitable for relational data, integrating related information scattered across different tables.
Word meaning: merge means "merge" or "blend"; here it refers to combining two data tables based on a common key.
Basic syntax and parameters
pd.merge() is a top-level function of the Pandas library, used to implement operations similar to JOIN in SQL.
Syntax format
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)
Parameter Description
- Parameters:
left - Type: DataFrame.
- Description: the left DataFrame, the first table involved in the merge.
- Parameters:
right - Type: DataFrame.
- Description: the right DataFrame, the second table involved in the merge.
- Parameters:
on - Type: string or list of strings.
- Description: the column name(s) used for joining (the key). Both the left and right DataFrames must have columns with the same name. If not specified, same-named columns are automatically found and used as keys.
- Parameters:
how - Type: string ('left', 'right', 'outer', 'inner').
- Description: the merge method, similar to SQL JOIN types.
'inner'indicates an inner join (intersection),'outer'indicates an outer join (union),'left'indicates a left join (keep all records from the left table),'right'indicates a right join (keep all records from the right table). The default is'inner'。
- Parameters:
left_on - Type: string or list of strings.
- Description: the column name(s) in the left DataFrame used as the join key. Used when the join key columns have different names in the left and right tables.
- Parameters:
right_on - Type: string or list of strings.
- Description: the column name(s) in the right DataFrame used as the join key. Used when the join key columns have different names in the left and right tables.
- Parameters:
suffixes - Type> tuple.
- Description> the suffix used to distinguish same-named columns (that are not join keys) in the left and right tables. The default is
('_x', '_y')。
Function description
- Return Value: returns the merged DataFrame.
- effect: horizontally merges two DataFrames into one according to the specified keys and method.
Example
Let us thoroughly master pd.merge() through a series of examples from simple to complex.
Example 1: basic usage - inner join based on a single column
Example
import
pandas
as
pd
1. Create two DataFrames
employees
=
pd.
DataFrame
(
{
'emp_id'
:
[
101
,
102
,
103
,
104
]
,
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'Diana'
]
,
'dept_id'
:
[
1
,
2
,
1
,
2
]
}
)
departments
=
pd.
DataFrame
(
{
'dept_id'
:
[
1
,
2
,
3
]
,
'dept_name'
:
[
'Engineering'
,
'Sales'
,
'Marketing'
]
}
)
(
"=== employee table (employees) ==="
)
(
employees
)
(
"\n=== department table (departments) ==="
)
(
departments
)
2. Use pd.merge() to merge based on the dept_id column (inner join, the default)
result
=
pd.
merge
(
employees
,
departments
,
on
=
'dept_id'
)
(
"\n=== pd.merge(employees, departments, on='dept_id') inner join ==="
)
(
result
)
Expected output:
=== 员工表 (employees) ===
emp_id name dept_id
0 101 Alice 1
1 102 Bob 2
2 103 Charlie 1
3 104 Diana 2
=== 部门表 (departments) ===
dept_id dept_name
0 1 Engineering
1 2 Sales
2 3 Marketing
=== pd.merge(employees, departments, on='dept_id') 内连接 ===
emp_id name dept_id dept_name
0 101 Alice 1 Engineering
1 103 Charlie 1 Engineering
2 102 Bob 2 Sales
3 104 Diana 2 Sales
Code analysis:
- The two tables are joined through the
dept_idcolumn, which is their common column. - By default, an inner join is used (
how='inner'), keeping only keys present on both sides (dept_id 1 and 2), so the marketing department with dept_id 3 is excluded. - After merging, each employee is associated with the corresponding department name.
Example 2: left join and right join
Use how The parameter controls the merge method and keeps all records from one side.
Example
import
pandas
as
pd
Continue using the data above
employees
=
pd.
DataFrame
(
{
'emp_id'
:
[
101
,
102
,
103
,
104
]
,
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'Diana'
]
,
'dept_id'
:
[
1
,
2
,
1
,
2
]
}
)
departments
=
pd.
DataFrame
(
{
'dept_id'
:
[
1
,
2
,
3
]
,
'dept_name'
:
[
'Engineering'
,
'Sales'
,
'Marketing'
]
}
)
1. Left join - keep all records from the left table
(
"=== left join (how='left') ==="
)
left_result
=
pd.
merge
(
employees
,
departments
,
on
=
'dept_id'
,
how
=
'left'
)
(
left_result
)
2. Right join - keep all records from the right table
(
"\n=== right join (how='right') ==="
)
right_result
=
pd.
merge
(
employees
,
departments
,
on
=
'dept_id'
,
how
=
'right'
)
(
right_result
)
3. Outer join - keep all records from both tables
(
"\n=== outer join (how='outer') ==="
)
outer_result
=
pd.
merge
(
employees
,
departments
,
on
=
'dept_id'
,
how
=
'outer'
)
(
outer_result
)
Expected output:
=== 左连接 (how='left') ===
emp_id name dept_id dept_name
0 101 Alice 1 Engineering
1 103 Charlie 1 Engineering
2 102 Bob 2 Sales
3 104 Diana 2 Sales
=== 右连接 (how='right') ===
emp_id name dept_id dept_name
0 101 Alice 1 Engineering
1 103 Charlie 1 Engineering
2 102 Bob 2 Sales
3 104 Diana 2 Sales
4 NaN NaN 3 Marketing
=== 外连接 (how='outer') ===
emp_id name dept_id dept_name
0 101 Alice 1 Engineering
1 103 Charlie 1 Engineering
2 102 Bob 2 Sales
3 104 Diana 2 Sales
4 NaN NaN 3 Marketing
Code analysis:
- A left join keeps all employee records from the left table (employees); departments with no match in the right table are shown as
NaN。 - A right join keeps all departments in the right table (departments), even if no employees belong to them.
- An outer join keeps all records from both tables; unmatched fields are filled with
NaNmissing values.
Example 3: handling two tables with different column names
When the join key columns have different names in the two tables, you can use left_on and right_on to specify them separately.
Example
import
pandas
as
pd
1. Create two DataFrames with different column names
students
=
pd.
DataFrame
(
{
'student_id'
:
[
1
,
2
,
3
,
4
]
,
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'Diana'
]
,
'class_id'
:
[
101
,
102
,
101
,
103
]
}
)
classes
=
pd.
DataFrame
(
{
'class_id'
:
[
101
,
102
,
103
]
,
'class_name'
:
[
'Class A'
,
'Class B'
,
'Class C'
]
,
'teacher'
:
[
'Mr. Smith'
,
'Ms. Johnson'
,
'Mrs. Lee'
]
}
)
(
"=== student table ==="
)
(
students
)
(
"\n=== class table ==="
)
(
classes
)
2. Use left_on and right_on to handle different column names
result
=
pd.
merge
(
students
,
classes
,
left_on
=
'class_id'
,
right_on
=
'class_id'
)
(
"\n=== merge with different column names ==="
)
(
result
)
Expected output:
=== 学生表 ===
student_id name class_id
0 1 Alice 101
1 2 Bob 102
2 3 Charlie 101
3 4 Diana 103
=== 班级表 ===
class_id class_name teacher
0 101 Class A Mr. Smith
1 102 Class B Ms. Johnson
2 103 Class C Mrs. Lee
=== 不同列名时的合并 ===
student_id name class_id class_name teacher
0 1 Alice 101 Class A Mr. Smith
1 3 Charlie 101 Class A Mr. Smith
2 2 Bob 102 Class B Indicator False
3 indicator column
print("\n=== indicator=True 显示合并详情 ===")
print(result_indicator)
[/mycode4]
运行结果预期:
=== 索引作为连接键 ===
name city score subject grade
0 Alice Beijing 85 Math A
1 Bob Shanghai 90 Math B
2 Charlie Guangzhou 95 English A
3 Diana Shenzhen 88 English B
=== 多个键的合并 ===
student_id name course_id course_name score
0 1 Alice 101 Math 90
1 1 Alice 102 English 85
2 2 Bob 101 Math 88
3 2 Bob 103 Science 92
4 3 Charlie 102 English 95
=== indicator=True 显示合并详情 ===
name city merge_info
0 Alice Beijing both
1 Bob Shanghai both
2 Charlie Guangzhou left_only
3 Diana Shenzhen left_only
Code analysis:
- Use
left_index=Trueandright_index=TrueYou can use the index of the DataFrame as the join key. - Pass a list to
onThis parameter enables merging on multiple keys, and a record is retained only when all keys match. - Settings
indicator=TrueYou can add a special column that shows which table each record comes from (left_only, right_only, both).
Tip:
pd.merge()Applies to column-based merge operations. If you only need to append data vertically (add rows), usepd.concat()function in Vue 3.
Common Pandas functions