Pandas Join vs. Merge: What’s the Difference?


Both the join() and the merge() functions can be used to combine two pandas DataFrames.

Here’s the main difference between the two functions:

  • The join() function combines two DataFrames by index.
  • The merge() function combines two DataFrames by whatever column you specify.

These functions use the following basic syntax:

#use join() to combine two DataFrames by index
df1.join(df2)

#use merge() to combine two DataFrames by specific column name
df1.merge(df2, on='column_name')

In cases where you know that you want to join two DataFrames by index, the join() function can be used to save some typing.

The following examples show how to use each function in practice.

Example 1: How to Use the join() Function

The following code shows how to use the join() function to combine two DataFrames:

import pandas as pd

#create two DataFrames
df1 = pd.DataFrame({'name': ['A', 'B', 'C'], 'points': [8, 12, 19]}).set_index('name')
df2 = pd.DataFrame({'name': ['A', 'B', 'C'], 'steals': [4, 5, 2]}).set_index('name')

#view two DataFrames
print(df1); print(df2)

      points                 steals
name                   name
A          8           A          4
B         12           B          5
C         19           C          2

#use join() function to join together two DataFrames
df1.join(df2)

	points	steals
name		
A	8	4
B	12	5
C	19	2

By default, the join() function joined together the two DataFrames using the index column.

Example 2: How to Use the merge() Function

The following code shows how to use the merge() function to combine two DataFrames:

import pandas as pd

#create two DataFrames
df1 = pd.DataFrame({'name': ['A', 'B', 'C'], 'points': [8, 12, 19]}).set_index('name')
df2 = pd.DataFrame({'name': ['A', 'B', 'C'], 'steals': [4, 5, 2]}).set_index('name')

#view two DataFrames
print(df1); print(df2)

      points                 steals
name                   name
A          8           A          4
B         12           B          5
C         19           C          2

#use join() function to join together two DataFrames
df1.merge(df2, on='name')

	points	steals
name		
A	8	4
B	12	5
C	19	2

Notice that the merge() function returned the exact same result, but we had to explicitly tell pandas to join the DataFrames using the ‘name’ column.

Additional Resources

You can find the complete online documentation for the join() and merge() functions here:

Documentation for join() function
Documentation for merge() function

The following tutorials explain how to perform other common functions in pandas:

How to Add Rows to a Pandas DataFrame
How to Add Header Row to Pandas DataFrame
How to Get First Row of Pandas DataFrame
How to Get First Column of Pandas DataFrame

Leave a Reply

Your email address will not be published.