Module 10: Merging and Joining Data
Learning Objectives
By the end of this module, you will be able to:
Combine DataFrames using
pd.merge()with inner, outer, left, and right joinsUnderstand one-to-one, one-to-many, and many-to-many relationships
Use
.join()for index-based mergingConcatenate datasets with
pd.concat()Append rows with
.append()(deprecated) andpd.concat()Handle overlapping columns and indices during combination
Note
Real-world data is rarely contained in a single table. Merging and joining are essential skills for combining information from multiple sources into a unified dataset for analysis.
The pd.merge() Function
pd.merge() is the primary workhorse for combining DataFrames based on common columns or indices. It follows SQL-style join semantics.
import pandas as pd
import numpy as np
# Two related tables
customers = pd.DataFrame({
"CustomerID": [1, 2, 3, 4, 5],
"Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
"City": ["New York", "London", "Paris", "Tokyo", "Sydney"],
})
orders = pd.DataFrame({
"OrderID": [101, 102, 103, 104, 105],
"CustomerID": [1, 2, 2, 4, 6],
"Amount": [250, 450, 300, 700, 150],
"Date": ["2024-01-15", "2024-02-20", "2024-03-10", "2024-04-05", "2024-05-01"],
})
print("Customers:")
print(customers)
print("\nOrders:")
print(orders)
Types of Joins
Inner join
Returns only rows with matching keys in both DataFrames.
inner = pd.merge(customers, orders, on="CustomerID", how="inner")
print(inner)
Left join
Returns all rows from the left DataFrame, with NaN for non-matching right rows.
left = pd.merge(customers, orders, on="CustomerID", how="left")
print(left)
Right join
Returns all rows from the right DataFrame, with NaN for non-matching left rows.
right = pd.merge(customers, orders, on="CustomerID", how="right")
print(right)
Outer join (full outer)
Returns all rows from both DataFrames, filling NaN where no match exists.
outer = pd.merge(customers, orders, on="CustomerID", how="outer")
print(outer)
Tip
Think of the how parameter as: which DataFrame’s rows should I keep all of? "left" keeps all left rows, "right" keeps all right rows, "inner" keeps only matches, and "outer" keeps everything.
Join Types Visualised
Join Type |
Left Rows |
Right Rows |
Matched Only |
|---|---|---|---|
Inner |
Only matched |
Only matched |
Yes |
Left |
All |
Only matched |
No |
Right |
Only matched |
All |
No |
Outer |
All |
All |
No |
Merging on Different Column Names
orders_alt = orders.rename(columns={"CustomerID": "CID"})
# Specify left and right columns
merged = pd.merge(customers, orders_alt, left_on="CustomerID", right_on="CID", how="inner")
print(merged)
Merging on Multiple Columns
df1 = pd.DataFrame({
"Year": [2020, 2020, 2021, 2021],
"Quarter": ["Q1", "Q2", "Q1", "Q2"],
"Revenue": [100, 120, 150, 130],
})
df2 = pd.DataFrame({
"Year": [2020, 2020, 2021, 2021],
"Quarter": ["Q1", "Q2", "Q1", "Q2"],
"Expenses": [80, 90, 110, 100],
})
# Merge on multiple key columns
merged = pd.merge(df1, df2, on=["Year", "Quarter"], how="inner")
print(merged)
Handling Overlapping Column Names
When both DataFrames have columns with the same name (other than the join key), Pandas adds suffixes.
df_a = pd.DataFrame({"ID": [1, 2, 3], "Value": [10, 20, 30], "Source": ["A", "A", "A"]})
df_b = pd.DataFrame({"ID": [2, 3, 4], "Value": [25, 35, 45], "Source": ["B", "B", "B"]})
# Custom suffixes
merged = pd.merge(df_a, df_b, on="ID", how="outer", suffixes=("_left", "_right"))
print(merged)
Warning
Always specify suffixes explicitly when merging DataFrames that share column names. The default suffixes _x and _y are not descriptive and can lead to confusion.
Index-Based Merge with .join()
.join() combines DataFrames based on their index labels.
df_index = customers.set_index("CustomerID")
orders_index = orders.set_index("CustomerID")
# Join on index
joined = df_index.join(orders_index, how="inner")
print(joined)
Joining on index with a column from another
# Mix index and column joins
result = customers.set_index("CustomerID").join(
orders.set_index("CustomerID"),
how="left",
)
print(result)
pd.concat() — Concatenating Along an Axis
Row-wise concatenation (stacking)
q1 = pd.DataFrame({"Product": ["A", "B"], "Sales": [100, 150]})
q2 = pd.DataFrame({"Product": ["A", "B"], "Sales": [120, 140]})
q3 = pd.DataFrame({"Product": ["A", "B", "C"], "Sales": [130, 160, 90]})
# Stack rows
yearly = pd.concat([q1, q2, q3], ignore_index=True)
print(yearly)
Column-wise concatenation
sales_2023 = pd.DataFrame({"Product": ["A", "B", "C"], "Sales_2023": [400, 450, 300]})
sales_2024 = pd.DataFrame({"Product": ["A", "B", "C"], "Sales_2024": [480, 520, 350]})
combined = pd.concat([sales_2023, sales_2024], axis=1)
print(combined)
Handling index labels
# With keys to identify source
combined = pd.concat(
[q1, q2, q3],
keys=["Q1", "Q2", "Q3"],
names=["Quarter", "Index"],
)
print(combined)
Tip
Use keys with pd.concat() to create a MultiIndex that tracks which source each row came from — invaluable for traceability.
Appending Data
While df.append() is deprecated, the same functionality is achieved with pd.concat().
# Old way (deprecated):
# df1.append(df2)
# Modern equivalent:
result = pd.concat([df1, df2], ignore_index=True)
Warning
Pandas deprecated .append() in version 1.4.0 and removed it in 2.0. Always use pd.concat() for appending rows.
One-to-Many and Many-to-Many Relationships
One-to-many merge
# One customer → many orders
customer_orders = pd.merge(customers, orders, on="CustomerID", how="inner")
print(f"One-to-many result shape: {customer_orders.shape}")
print(customer_orders)
Many-to-many merge
# Products and categories (many-to-many)
products = pd.DataFrame({"Product": ["A", "B", "C"], "Price": [10, 20, 30]})
categories = pd.DataFrame({
"Product": ["A", "A", "B", "C", "C", "C"],
"Category": ["X", "Y", "X", "X", "Y", "Z"],
})
result = pd.merge(products, categories, on="Product", how="inner")
print(result)
Note
A many-to-many merge produces the Cartesian product of matching keys. Be cautious — if not expected, it can blow up the result size dramatically.
Validating Merge Relationships
# Use validate to check merge assumptions
try:
pd.merge(customers, orders, on="CustomerID", how="inner", validate="one_to_one")
except pd.errors.MergeError as e:
print(f"Validation error: {e}")
# This will work (one customer can have many orders)
pd.merge(customers, orders, on="CustomerID", how="inner", validate="one_to_many")
Practical Example: Sales Data Warehouse
# Simulate a star-schema data warehouse
np.random.seed(42)
# Dimension tables
products = pd.DataFrame({
"ProductID": range(1, 6),
"ProductName": ["Widget", "Gadget", "Doohickey", "Thingamajig", "Whatsit"],
"Category": ["Tools", "Electronics", "Tools", "Electronics", "Misc"],
})
stores = pd.DataFrame({
"StoreID": ["S01", "S02", "S03"],
"StoreName": ["Downtown", "Uptown", "Midtown"],
"City": ["New York", "Los Angeles", "Chicago"],
})
# Fact table
transactions = pd.DataFrame({
"TransactionID": range(1, 101),
"ProductID": np.random.randint(1, 6, 100),
"StoreID": np.random.choice(["S01", "S02", "S03"], 100),
"Quantity": np.random.randint(1, 10, 100),
"Price": np.round(np.random.uniform(5, 100, 100), 2),
"Date": pd.date_range("2024-01-01", periods=100, freq="D"),
})
# Build the star-schema query
enriched = (
transactions
.merge(products, on="ProductID", how="left")
.merge(stores, on="StoreID", how="left")
)
# Category sales by city
report = enriched.groupby(["City", "Category"])["Quantity"].sum().unstack(fill_value=0)
print(report)
Summary
pd.merge()provides SQL-style joins (inner, left, right, outer) based on common columnsUse
left_on/right_onwhen key columns have different namesMerge on multiple keys by passing a list to
on.join()is a convenience method for index-based mergespd.concat()stacks DataFrames row-wise (axis=0) or column-wise (axis=1)Use
suffixesto disambiguate overlapping column namesValidate merge cardinality with the
validateparameter
Exercises
Using these DataFrames:
import pandas as pd
import numpy as np
employees = pd.DataFrame({
"EmpID": [101, 102, 103, 104, 105],
"Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
"DeptID": [10, 20, 10, 30, 20],
})
departments = pd.DataFrame({
"DeptID": [10, 20, 30, 40],
"DeptName": ["Engineering", "Marketing", "Sales", "HR"],
"Budget": [500000, 300000, 400000, 200000],
})
salaries = pd.DataFrame({
"EmpID": [101, 102, 103, 104, 106],
"Salary": [75000, 65000, 82000, 70000, 55000],
"Bonus": [5000, 3000, 6000, 4000, 2000],
})
Merge employees with departments to show each employee’s department name
Merge employees with salaries using a left join — who is missing salary data?
Perform a full outer join of employees and salaries — which employees have no salary record and which salaries have no employee?
Concatenate a list of DataFrames
[q1_sales, q2_sales, q3_sales, q4_sales]into a single yearly DataFrame with aQuarterkey columnUse
.join()to mergeemployees.set_index("EmpID")withsalaries.set_index("EmpID")Create a report showing average salary by department using merges and groupby