🎓 A1Learner
🔍
0 of 50 lessons completed

Merging on a Key

merge joins two tables on a shared column. The shared column is the key, and rows match when their keys are equal.

Join sales to costs

merge matches each order to its cost by product. The cost column joins the orders.

import pandas as pd

orders = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
    "price": [4.50, 6.00, 12.00],
})
costs = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "cost": [2.00, 3.00, 6.00],
})
print(orders.merge(costs, on="product"))

Add a profit column

Each row now holds a price and a cost. Profit is units times price minus cost.

import pandas as pd

orders = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
    "price": [4.50, 6.00, 12.00],
})
costs = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "cost": [2.00, 3.00, 6.00],
})
merged = orders.merge(costs, on="product")
merged["profit"] = merged["units"] * (merged["price"] - merged["cost"])
print(merged)

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

PRODUCTS_CSV = """product,category,cost
Tea,Drink,2.00
Coffee,Drink,3.00
Mug,Home,6.00
Notebook,Office,4.00
Pen,Office,0.80
Lamp,Home,15.00"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
products = pd.read_csv(io.StringIO(PRODUCTS_CSV))
costs = products[["product", "cost"]]
merged = sales.merge(costs, on="product")
merged["profit"] = merged["units"] * (merged["price"] - merged["cost"])
print(merged[["order_id", "product", "units", "price", "cost", "profit"]].head(6))
print(merged["profit"].sum())

Key points

  • Use merge to join two tables on a shared column.
  • Pass on to merge to name the shared column.
  • An inner join keeps only rows with a match on both sides.
  • The key column appears once in the joined table.
  • Pick the lookup columns first to keep the joined table tidy.

In this example, the sales table and the products table load from CSV text. The costs frame keeps only product and cost. merge joins each order to its cost by product. Profit is units times price minus cost, and the total profit is 105.9.

Note

Inner is the default join. merge without a type keeps only matching rows.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which call joins orders to costs on the product column?