w3resource

Merging Multiple DataFrames on a Common Column in Pandas

Pandas: Custom Function Exercise-10 with Solution

Write a Pandas program to merge multiple DataFrames on a common column.

Following exercise shows how to merge three DataFrames on a common column.

Sample Solution :

Code :

import pandas as pd

# Create three sample DataFrames
df1 = pd.DataFrame({
    'ID': [1, 2, 3],
    'Name': ['Selena', 'Annabel', 'Caeso']
})

df2 = pd.DataFrame({
    'ID': [1, 2, 3],
    'Age': [25, 30, 22]
})

df3 = pd.DataFrame({
    'ID': [1, 2, 3],
    'Salary': [50000, 60000, 70000]
})

# Merge the three DataFrames on the 'ID' column
merged_df = pd.merge(pd.merge(df1, df2, on='ID'), df3, on='ID')

# Output the result
print(merged_df)

Output:

   ID     Name  Age  Salary
0   1   Selena   25   50000
1   2  Annabel   30   60000
2   3    Caeso   22   70000        

Explanation:

  • Created three DataFrames df1, df2, and df3 with a common column 'ID'.
  • Used pd.merge() twice to merge all three DataFrames on the 'ID' column.
  • The result is a merged DataFrame that includes data from all three DataFrames.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/pandas-merge-multiple-dataframes-on-a-common-column.php