0
0
Pandasdata~5 mins

Right join behavior in Pandas

Choose your learning style9 modes available
Introduction
A right join helps you combine two tables by keeping all rows from the second table and matching rows from the first table.
You want to keep all records from the second table even if there is no match in the first table.
You have sales data and want to add employee info, but keep all sales even if there is no matching employee.
You want to combine customer orders with shipment details, keeping all shipment records even if some orders are missing.
You want to see all products in stock and add supplier info, keeping all suppliers even if some products are missing.
Syntax
Pandas
pd.merge(left_df, right_df, how='right', on='key_column')
The 'how' parameter controls the type of join; 'right' means keep all rows from right_df.
The 'on' parameter specifies the column(s) to join on; both dataframes should have this column.
Examples
Joins df1 and df2 keeping all rows from df2 based on 'id' column.
Pandas
pd.merge(df1, df2, how='right', on='id')
Keeps all sales records and adds employee info where available.
Pandas
pd.merge(employees, sales, how='right', on='employee_id')
Keeps all suppliers and adds product info if it exists.
Pandas
pd.merge(products, suppliers, how='right', on='supplier_id')
Sample Program
This code merges two dataframes keeping all rows from right_df. The row with id=4 is kept even though it has no match in left_df.
Pandas
import pandas as pd

left_df = pd.DataFrame({
    'id': [1, 2, 3],
    'name': ['Alice', 'Bob', 'Charlie']
})

right_df = pd.DataFrame({
    'id': [2, 3, 4],
    'score': [88, 92, 75]
})

result = pd.merge(left_df, right_df, how='right', on='id')
print(result)
OutputSuccess
Important Notes
If there is no matching row in the left dataframe, pandas fills missing values with NaN.
Right join is useful when the second table has important data you want to keep fully.
You can join on multiple columns by passing a list to 'on'.
Summary
Right join keeps all rows from the right dataframe.
Matching rows from the left dataframe are added where possible.
Missing matches in the left dataframe show as NaN.