We use merge() to combine two tables based on common columns, just like joining tables in a database. It helps us see related data together.
merge() for SQL-like joins in Pandas
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None)
left and right are the two tables (DataFrames) to join.
how decides the type of join: 'inner', 'left', 'right', or 'outer'.
pd.merge(df1, df2, on='id')df1 and add matching rows from df2.pd.merge(df1, df2, how='left', on='id')
pd.merge(df1, df2, how='outer', on='id')
pd.merge(df1, df2, left_on='user_id', right_on='id')
This code shows how to join two tables of users and orders using different join types. It prints the results so you can see how rows match or stay when no match is found.
import pandas as pd # Create first table with user info df_users = pd.DataFrame({ 'user_id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Charlie'] }) # Create second table with orders df_orders = pd.DataFrame({ 'order_id': [101, 102, 103, 104], 'user_id': [2, 2, 3, 4], 'product': ['Book', 'Pen', 'Notebook', 'Pencil'] }) # Merge tables to see orders with user names merged_inner = pd.merge(df_users, df_orders, on='user_id') merged_left = pd.merge(df_users, df_orders, how='left', on='user_id') merged_outer = pd.merge(df_users, df_orders, how='outer', on='user_id') print('Inner Join Result:') print(merged_inner) print('\nLeft Join Result:') print(merged_left) print('\nOuter Join Result:') print(merged_outer)
If columns have different names, use left_on and right_on to specify them.
Inner join keeps only matching rows; left join keeps all from left table; right join keeps all from right table; outer join keeps all rows from both.
Missing matches fill with NaN, which means 'no data'.
merge() combines two tables based on matching columns.
You can choose how to join: inner, left, right, or outer.
It helps you see related data from different sources together easily.
Practice
merge() function in pandas do?Solution
Step 1: Understand the purpose of merge()
Themerge()function is designed to combine two tables (DataFrames) by matching values in specified columns.Step 2: Compare with other options
Sorting, filtering, and changing data types are different operations and not the main purpose ofmerge().Final Answer:
It combines two DataFrames based on matching columns. -> Option DQuick Check:
merge() joins tables on columns [OK]
- Confusing merge() with sort or filter functions
- Thinking merge() changes data types
- Assuming merge() works without matching columns
df1 and df2 on column 'id' using pandas?Solution
Step 1: Recall correct merge syntax
The correct pandas syntax for merging ispd.merge(left, right, on=column, how=type). Here,how='inner'specifies an inner join.Step 2: Check each option
pd.merge(df1, df2, on='id', how='inner') matches the correct syntax. df1.merge(df2, by='id', join='inner') uses wrong parameter names. pd.join(df1, df2, on='id', how='inner') usespd.joinwhich does not exist. df1.merge(df2, on='id', how='outer') useshow='outer'which is not inner join.Final Answer:
pd.merge(df1, df2, on='id', how='inner') -> Option BQuick Check:
Correct merge syntax = pd.merge(df1, df2, on='id', how='inner') [OK]
- Using wrong parameter names like 'by' or 'join'
- Confusing merge() with join() method
- Mixing up 'inner' and 'outer' join types
import pandas as pd
df1 = pd.DataFrame({'id': [1, 2, 3], 'value1': ['A', 'B', 'C']})
df2 = pd.DataFrame({'id': [2, 3, 4], 'value2': ['X', 'Y', 'Z']})
result = pd.merge(df1, df2, on='id', how='inner')
print(result)What will be the output?
Solution
Step 1: Understand inner join behavior
An inner join keeps only rows with matching 'id' values in both DataFrames. Here, common ids are 2 and 3.Step 2: Check matching rows and columns
Rows with id 2 and 3 appear in both df1 and df2, so their columns combine. Rows with id 1 or 4 are excluded.Final Answer:
id value1 value2 0 2 B X 1 3 C Y -> Option AQuick Check:
Inner join keeps only matching ids [OK]
- Expecting all rows from both DataFrames
- Confusing inner join with left or outer join
- Ignoring NaN values in output
import pandas as pd
df1 = pd.DataFrame({'key1': [1, 2], 'val': ['A', 'B']})
df2 = pd.DataFrame({'key2': [1, 2], 'val': ['X', 'Y']})
result = pd.merge(df1, df2, on='key1', how='inner')What is the cause of the error?
Solution
Step 1: Check columns in both DataFrames
df1 has column 'key1', but df2 has 'key2'. The merge tries to join on 'key1' which df2 lacks.Step 2: Understand KeyError cause
Because 'key1' is missing in df2, pandas raises a KeyError indicating the column is not found.Final Answer:
Column 'key1' does not exist in df2. -> Option AQuick Check:
Merge keys must exist in both DataFrames [OK]
- Assuming merge works with different column names without specifying
- Thinking 'how' parameter causes KeyError
- Believing row counts must match to merge
df_customers = pd.DataFrame({'customer_id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Charlie']})
df_orders = pd.DataFrame({'order_id': [101, 102, 103], 'customer_id': [2, 2, 4], 'amount': [250, 125, 300]})You want to create a DataFrame showing all customers and their orders, including customers with no orders and orders with no matching customer. Which
merge() call achieves this?Solution
Step 1: Understand join types
An outer join keeps all rows from both DataFrames, filling missing matches with NaN.Step 2: Apply to problem context
We want all customers (even without orders) and all orders (even without matching customers). Only outer join includes all rows from both sides.Final Answer:
pd.merge(df_customers, df_orders, on='customer_id', how='outer') -> Option CQuick Check:
Outer join includes all rows from both tables [OK]
- Using inner join excludes unmatched rows
- Left join excludes orders without customers
- Right join excludes customers without orders
Ready to prove it?
Pass the test and this pattern moves unknown
