Ravindra BagaleCourses & study guides मराठी Track your progress

28. How to Merge and Join Tables in pandas for Blinkit Data

Data Science

28.5 Three-Table Path: orders ⨝ stores ⨝ riders

Why. Delivery SLA stories need store city and rider name. Chain merges carefully — one validated step at a time.

What. Merge orders→stores, check length, then merge→riders on rider_id. Prefer left joins from the fact table.

How.

Chain with checkpoints

  1. o_s = orders.merge(stores, on="store_id", how="left", indicator="store_merge").
  2. Assert len(o_s) == len(orders) (after proving stores keys unique).
  3. o_sr = o_s.merge(riders, on="rider_id", how="left", indicator="rider_merge").
  4. Assert length again.
  5. Summarise unmatched store vs rider separately.

Worked example A — Chain.

import pandas as pd

orders = pd.DataFrame({
    "order_id": ["BLK-1", "BLK-2", "BLK-3"],
    "store_id": ["PUN-01", "NSK-01", "PUN-01"],
    "rider_id": ["R-9", "R-2", "R-9"],
    "amount_inr": [100, 90, 80],
})
stores = pd.DataFrame({
    "store_id": ["PUN-01", "NSK-01"],
    "city": ["Pune", "Nashik"],
})
riders = pd.DataFrame({
    "rider_id": ["R-9", "R-2"],
    "rider_name": ["Salman", "Zoya"],
})

o_s = orders.merge(stores, on="store_id", how="left")
assert len(o_s) == len(orders)
o_sr = o_s.merge(riders, on="rider_id", how="left")
assert len(o_sr) == len(orders)
print(o_sr)

Worked example B — GMV by city and rider.

g = (
    o_sr.groupby(["city", "rider_name"], as_index=False)["amount_inr"]
    .sum()
    .sort_values("amount_inr", ascending=False)
)
print(g)

Worked example C — Stop if length jumps.

If len grows, halt and run the duplicate-key check — do not “fix with a chart”.

Ravindra Bagale's Tip

Do one merge, then one check: assert that the row count still equals the number of orders. With three tables you need two checkpoints, one after joining stores and one after joining riders. Give the middle tables clear names like orders_stores instead of df2 or df3, and stop at once if the length jumps.