Merging two DataFrames on a single column in Pandas
1. Merge on Single Column
Write a Pandas program to merge two DataFrames on a single column.
In this exercise, we have merged two DataFrames on a single common column 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']
})
df2 = pd.DataFrame({
'ID': [2, 3, 4],
'Age': [25, 30, 22]
})
# Merge the two DataFrames on the 'ID' column
merged_df = pd.merge(df1, df2, on='ID')
# Output the result
print(merged_df)
Output:
ID Name Age 0 2 Annabel 25 1 3 Caeso 30
Explanation:
- Created two DataFrames df1 and df2 with a common column 'ID'.
- Used pd.merge() to merge the two DataFrames on the 'ID' column.
- The result includes rows where 'ID' exists in both DataFrames, joining on the common values.
For more Practice: Solve these Related Problems:
- Write a Pandas program to merge two DataFrames on a single column ensuring that duplicate entries in the left DataFrame are preserved.
- Write a Pandas program to merge two DataFrames on a single column with case‐insensitive matching on string keys.
- Write a Pandas program to merge two DataFrames on a single column and then filter out rows where the merge key appears only once in the right DataFrame.
- Write a Pandas program to merge two DataFrames on a single column and drop rows with null values in the merge key column after the merge.
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.