Merging two DataFrames on a single column in Pandas
Pandas: Custom Function Exercise-1 with Solution
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.
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