Merging two DataFrames on multiple columns using merge() in Pandas
5. Merge on Multiple Columns
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to merge two DataFrames on two columns and handle overlapping column names using custom suffixes.
- Write a Pandas program to merge two DataFrames on multiple columns and filter rows where key columns have inconsistent data types.
- Write a Pandas program to merge two DataFrames on multiple columns and then sort the merged DataFrame by one of the key columns.
- Write a Pandas program to merge two DataFrames on multiple columns with string keys in a case‐insensitive manner.
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.