Joining tables with merge
Match rows from two tables using a shared key.
Sometimes the facts you need live in two different tables: orders list a product_id and quantity, while a products table lists each product_id’s name and price. merge joins them by matching a shared key column. orders.merge(products, on="product_id") adds the product columns to every order. By default (how="inner") only rows with a match in both tables are kept. how="left" keeps every row of the left table and fills NaN when there is no match, which helps you spot missing information.
import pandas as pd
orders = pd.DataFrame({"order": [1, 2, 3, 4], "product_id": ["P1", "P2", "P1", "P9"], "qty": [2, 1, 5, 3]})
products = pd.DataFrame({"product_id": ["P1", "P2", "P3"], "name": ["Pen", "Notebook", "Ruler"], "price": [1.5, 4.0, 2.25]})
inner = orders.merge(products, on="product_id")
print(inner)
left = orders.merge(products, on="product_id", how="left")
print(left)The inner merge has 3 rows: order 4 (P9) disappears because P9 is not in products. The left merge keeps all 4 orders; order 4 gets NaN for name and price, which flags a product missing from the catalog.
After merging, compute new columns as usual, for example merged["revenue"] = merged["qty"] * merged["price"].
If the key has different names in the two tables, use left_on="id" and right_on="product_id".