Merging DataFrames with different join column names in Pandas
8. Merge Diff Column Names
Write a Pandas program to merge different column names in DataFrames.
In this exercise, we have merged two DataFrames where the column names we want to join on are different in each DataFrame.
Sample Solution :
Code :
import pandas as pd
# Create two sample DataFrames with different join column names
df1 = pd.DataFrame({
'Employee_ID': [1, 2, 3],
'Name': ['Selena', 'Annabel', 'Caeso']
})
df2 = pd.DataFrame({
'ID': [1, 2, 3],
'Salary': [50000, 60000, 70000]
})
# Merge the DataFrames, specifying different column names for the join
merged_df = pd.merge(df1, df2, left_on='Employee_ID', right_on='ID')
# Output the result
print(merged_df)
Output:
Employee_ID Name ID Salary 0 1 Selena 1 50000 1 2 Annabel 2 60000 2 3 Caeso 3 70000
Explanation:
- Created two DataFrames df1 and df2 with different column names for the join ('Employee_ID' and 'ID').
- Used pd.merge() with the left_on and right_on arguments to specify which columns to join on.
- The result merges the DataFrames based on the specified column names.
For more Practice: Solve these Related Problems:
- Write a Pandas program to merge two DataFrames where the key columns have different names, using the left DataFrame's key as reference.
- Write a Pandas program to merge two DataFrames with different key column names and then validate the merge by comparing key frequencies.
- Write a Pandas program to merge two DataFrames on differently named key columns and drop duplicate key columns in the result.
- Write a Pandas program to merge two DataFrames on different column names and then rename the merged key column consistently.
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.