w3resource

Merging Multiple DataFrames on a Common Column in Pandas


10. Merge Multiple DataFrames

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to sequentially merge three DataFrames on a common column and then remove any resulting duplicates.
  • Write a Pandas program to merge multiple DataFrames on a common column and compute an aggregate statistic for a numeric column.
  • Write a Pandas program to merge multiple DataFrames on a common column using chained merges and then filter rows based on a condition from one DataFrame.
  • Write a Pandas program to merge multiple DataFrames on a common column and validate the merge by checking the total row count.

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.



Follow us on Facebook and Twitter for latest update.