BBampaa

Lessons › Python

Python lesson

Left joins

All 5 orders stay. Kano and Ibadan aren't in stores, so their Region and Manager are NaN (empty). Without how="left", those two orders would quietly vanish, and so would their 150 in revenue.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

how="left" keeps every row of the first table. Where there's no match, the new columns are empty:

merged = pd.merge(df, stores, on="Store", how="left")
merged

Output:

Order Store Revenue Region Manager
0 O301 Lagos 80 South-West Ada Obi
1 O302 Kano 60 NaN NaN
2 O303 Abuja 45 North Musa Bello
3 O304 Ibadan 90 NaN NaN
4 O305 Lagos 30 South-West Ada Obi

Key points

how="left"Keep every row of the first table, matched or not.
The defaultpd.merge without how keeps only the rows that match in both tables.
NaN after a left joinNo match was found for that row.
merged["Region"].isna()True for the rows that didn't match.

Left join with pd.merge(df, stores, on="Store", how="left"), then find the gaps with .isna().

Practice

Try each one in your head first, then open the answer.

1. Build a line that joins df to stores on Store, keeping every order.
pd.merge(df, stores, on="Store", how="left")
2. Build a line that shows only the orders that didn't match a store.
merged[merged["Region"].isna()]
3. Join df to stores on Store, keeping every order, and show the result.
pd.merge(df, stores, on="Store", how="left")
4. Show only the orders whose store isn't in the stores table.
merged = pd.merge(df, stores, on="Store", how="left")
merged[merged["Region"].isna()]
5. Show how many orders didn't match a store.
merged = pd.merge(df, stores, on="Store", how="left")
merged["Region"].isna().sum()

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed