Left and right joins help combine two tables based on a shared column. They keep all data from one table and add matching data from the other.
0
0
Left and right joins in Data Analysis Python
Introduction
You have customer data in one table and order data in another, and want all customers with their orders if any.
You want to keep all sales records and add product details where available.
You have employee info and department info, and want all employees listed even if some departments are missing.
You want to merge two lists but keep everything from one list regardless of matches.
Syntax
Data Analysis Python
pd.merge(left_df, right_df, how='left', on='key_column') pd.merge(left_df, right_df, how='right', on='key_column')
left join keeps all rows from the left table.
right join keeps all rows from the right table.
Examples
This keeps all rows from
left and adds score where id matches.Data Analysis Python
import pandas as pd left = pd.DataFrame({'id': [1, 2, 3], 'name': ['Anna', 'Bob', 'Cara']}) right = pd.DataFrame({'id': [2, 3, 4], 'score': [90, 80, 70]}) left_join = pd.merge(left, right, how='left', on='id') print(left_join)
This keeps all rows from
right and adds name where id matches.Data Analysis Python
import pandas as pd left = pd.DataFrame({'id': [1, 2, 3], 'name': ['Anna', 'Bob', 'Cara']}) right = pd.DataFrame({'id': [2, 3, 4], 'score': [90, 80, 70]}) right_join = pd.merge(left, right, how='right', on='id') print(right_join)
Sample Program
This program shows how left and right joins work. The left join keeps all people and adds scores if available. The right join keeps all scores and adds names if available.
Data Analysis Python
import pandas as pd # Create left table with people left = pd.DataFrame({ 'id': [1, 2, 3], 'name': ['Anna', 'Bob', 'Cara'] }) # Create right table with scores right = pd.DataFrame({ 'id': [2, 3, 4], 'score': [90, 80, 70] }) # Left join: keep all from left, add matching score left_join = pd.merge(left, right, how='left', on='id') print('Left Join Result:') print(left_join) # Right join: keep all from right, add matching name right_join = pd.merge(left, right, how='right', on='id') print('\nRight Join Result:') print(right_join)
OutputSuccess
Important Notes
If no match is found, missing values appear as NaN.
You can join on multiple columns by passing a list to on.
Use how='inner' to keep only matching rows from both tables.
Summary
Left join keeps all rows from the left table and adds matching data from the right.
Right join keeps all rows from the right table and adds matching data from the left.
Joins help combine related data from two tables based on common columns.