Merging DataFrames with different join column names in Pandas
Pandas: Custom Function Exercise-8 with Solution
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics