w3resource

Merging two DataFrames on multiple columns using merge() in Pandas


Pandas: Custom Function Exercise-5 with Solution


Write a Pandas program to merge two DataFrames on multiple columns.

In this exercise shows how to merge two DataFrames on multiple columns using pd.merge().

Sample Solution :

Code :

import pandas as pd

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

df2 = pd.DataFrame({
    'ID': [1, 2, 3],
    'Name': ['Selena', 'Annabel', 'Caeso'],
    'Salary': [50000, 60000, 70000]
})

# Merge the DataFrames on both 'ID' and 'Name' columns
merged_df = pd.merge(df1, df2, on=['ID', 'Name'])

# 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 two DataFrames df1 and df2 with common columns 'ID' and 'Name'.
  • Used pd.merge() to merge on both the 'ID' and 'Name' columns.
  • The result includes rows where both columns have matching values in both 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.



Follow us on Facebook and Twitter for latest update.