Merge & Join List of pandas DataFrames in Python (Example Code)

In this article you’ll learn how to combine a list of multiple pandas DataFrames in the Python programming language.

Setting up the Example

import pandas as pd                       # Import pandas library to Python
df1 = pd.DataFrame({"ID":range(1, 6),     # Construct three DataFrames
                    "A":range(11, 16),
                    "B":["g", "x", "g", "d", "f"]})
print(df1)
#    ID   A  B
# 0   1  11  g
# 1   2  12  x
# 2   3  13  g
# 3   4  14  d
# 4   5  15  f
df2 = pd.DataFrame({"ID":range(3, 8),
                    "C":["a", "y", "s", "x", "a"],
                    "D":range(12, 2, - 2)})
print(df2)
#    ID  C   D
# 0   3  a  12
# 1   4  y  10
# 2   5  s   8
# 3   6  x   6
# 4   7  a   4
df3 = pd.DataFrame({"ID":range(2, 10),
                    "E":range(10, 2, - 1),
                    "F":range(9, 1, - 1)})
print(df3)
#    ID   E  F
# 0   2  10  9
# 1   3   9  8
# 2   4   8  7
# 3   5   7  6
# 4   6   6  5
# 5   7   5  4
# 6   8   4  3
# 7   9   3  2
my_list = [df1, df2, df3]                 # Construct list object

Example: Joining Three pandas DataFrames in List in Python

from functools import reduce              # Loading reduce function
df_joined = reduce(lambda left, right:    # Merge multiple DataFrames in list
                    pd.merge(left , right,
                             on = ["ID"]),
                    my_list)
print(df_joined)
#    ID   A  B  C   D  E  F
# 0   3  13  g  a  12  9  8
# 1   4  14  d  y  10  8  7
# 2   5  15  f  s   8  7  6

Related Tutorials

Have a look at the following list of Python programming tutorials. They discuss topics such as variables, data conversion, and lists.

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