Join & Merge Two pandas DataFrames in Python (4 Examples)

On this page, I’ll show how to merge pandas DataFrames in the Python programming language.

Preparing the Examples

import pandas as pd                                            # Import pandas library in Python
df1 = pd.DataFrame({"ID":range(1, 4),                          # Construct two pandas DataFrames
                    "A":range(10, 13),
                    "B":range(13, 10, - 1)})
print(df1)
#    ID   A   B
# 0   1  10  13
# 1   2  11  12
# 2   3  12  11
df2 = pd.DataFrame({"ID":range(2, 6),
                    "C":["a", "s", "d", "f"],
                    "D":range(1, 5)})
print(df2)
#    ID  C  D
# 0   2  a  1
# 1   3  s  2
# 2   4  d  3
# 3   5  f  4

Example 1: Inner Join Two pandas DataFrames in Python

df_merge_inner = pd.merge(df1, df2, on = "ID", how = "inner")  # Merge DataFrames
print(df_merge_inner)
#    ID   A   B  C  D
# 0   2  11  12  a  1
# 1   3  12  11  s  2

Example 2: Outer Join Two pandas DataFrames in Python

df_merge_outer = pd.merge(df1, df2, on = "ID", how = "outer")  # Merge DataFrames
print(df_merge_outer)
#    ID     A     B    C    D
# 0   1  10.0  13.0  NaN  NaN
# 1   2  11.0  12.0    a  1.0
# 2   3  12.0  11.0    s  2.0
# 3   4   NaN   NaN    d  3.0
# 4   5   NaN   NaN    f  4.0

Example 3: Right Join Two pandas DataFrames in Python

df_merge_right = pd.merge(df1, df2, on = "ID", how = "right")  # Merge DataFrames
print(df_merge_right)
#    ID     A     B  C  D
# 0   2  11.0  12.0  a  1
# 1   3  12.0  11.0  s  2
# 2   4   NaN   NaN  d  3
# 3   5   NaN   NaN  f  4

Example 4: Left Join Two pandas DataFrames in Python

df_merge_left = pd.merge(df1, df2, on = "ID", how = "left")    # Merge DataFrames
print(df_merge_left)
#    ID   A   B    C    D
# 0   1  10  13  NaN  NaN
# 1   2  11  12    a  1.0
# 2   3  12  11    s  2.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top