w3resource

Performing a Right Join Between Two DataFrames in Pandas

Pandas: Custom Function Exercise-4 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-right-join-two-dataframes-to-include-all-rows.php