28. How to Merge and Join Tables in pandas for Blinkit Data
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
o_s = orders.merge(stores, on="store_id", how="left", indicator="store_merge").- Assert
len(o_s) == len(orders)(after proving stores keys unique). o_sr = o_s.merge(riders, on="rider_id", how="left", indicator="rider_merge").- Assert length again.
- 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
Ek merge, ek assert. Teen tables = don checkpoints.