Merge & Join Three pandas DataFrames in Python (Example Code)

In this Python tutorial you’ll learn how to merge multiple pandas DataFrames.

Preparing the Example

import pandas as pd                        # Import pandas library in Python
df1 = pd.DataFrame({"ID":range(1, 6),      # Construct three DataFrames
                    "A":range(111, 116),
                    "B":["a", "x", "ppp", "d", "f"]})
print(df1)
#    ID    A    B
# 0   1  111    a
# 1   2  112    x
# 2   3  113  ppp
# 3   4  114    d
# 4   5  115    f
df2 = pd.DataFrame({"ID":range(4, 8),
                    "C":["a", "s", "d", "a"],
                    "D":range(10, 2, - 2)})
print(df2)
#    ID  C   D
# 0   4  a  10
# 1   5  s   8
# 2   6  d   6
# 3   7  a   4
df3 = pd.DataFrame({"ID":range(2, 10),
                    "E":range(10, 2, - 1)})
print(df3)
#    ID   E
# 0   2  10
# 1   3   9
# 2   4   8
# 3   5   7
# 4   6   6
# 5   7   5
# 6   8   4
# 7   9   3

Example: Joining Three pandas DataFrames in Python

from functools import reduce               # Loading reduce function
data_merge = reduce(lambda left, right:    # Merge multipl DataFrames
                    pd.merge(left , right,
                             on = ["ID"],
                             how = "outer"),
                    [df1, df2, df3])
print(data_merge)
#    ID      A    B    C     D     E
# 0   1  111.0    a  NaN   NaN   NaN
# 1   2  112.0    x  NaN   NaN  10.0
# 2   3  113.0  ppp  NaN   NaN   9.0
# 3   4  114.0    d    a  10.0   8.0
# 4   5  115.0    f    s   8.0   7.0
# 5   6    NaN  NaN    d   6.0   6.0
# 6   7    NaN  NaN    a   4.0   5.0
# 7   8    NaN  NaN  NaN   NaN   4.0
# 8   9    NaN  NaN  NaN   NaN   3.0

Related Tutorials & Further Resources

In addition, you might read some of the related tutorials on my website. I have released several tutorials already:

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