Performing a Right Join Between Two DataFrames in Pandas
4. Right Join Merge
Write a Pandas program that performs a right join of two DataFrames.
This exercise shows how to perform a right join to include all rows from the right DataFrame and matching rows from the left.
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]
})
# Perform a right join on the 'ID' column
right_joined_df = pd.merge(df1, df2, on='ID', how='right')
# Output the result
print(right_joined_df)
Output:
ID Name Age 0 2 Annabel 25 1 3 Caeso 30 2 4 NaN 22
Explanation:
- Created two DataFrames df1 and df2.
- Used pd.merge() with how='right' to perform a right join.
- The result includes all rows from the right DataFrame and only the matching rows from the left DataFrame.
For more Practice: Solve these Related Problems:
- Write a Pandas program to perform a right join on two DataFrames and filter out rows that originate exclusively from the left DataFrame.
- Write a Pandas program to perform a right join on two DataFrames and calculate the average of a numeric column from the right DataFrame.
- Write a Pandas program to perform a right join on two DataFrames and pivot the resulting DataFrame based on a categorical column.
- Write a Pandas program to perform a right join on two DataFrames and merge columns with similar names using custom suffixes.
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.