BBampaa

Lessons › Python

Python lesson

Joining two tables

Every order now has its store's Region and Manager. The column you join on must have the same name in both tables.

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

Example

pd.merge puts two tables side by side, matching the rows on the column they share:

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

Output:

Order Day Store Product Qty Revenue Region Manager
0 O101 Mon Lagos Earbuds 2 70 South-West Ada Obi
1 O102 Mon Abuja Charger 1 15 North Musa Bello
2 O103 Tue Lagos Phone case 3 24 South-West Ada Obi
3 O104 Wed Lagos Earbuds 1 35 South-West Ada Obi
4 O105 Wed Abuja Earbuds 4 140 North Musa Bello
5 O106 Thu Lagos Charger 2 30 South-West Ada Obi
6 O107 Fri Abuja Phone case 5 40 North Musa Bello
7 O108 Fri Lagos Earbuds 3 105 South-West Ada Obi

Key points

pd.merge(df, storesThe two tables, the main one first.
on="Store"The column they share. Rows match where the store is the same.
how="left"Keep every row of the first table, even with no match. The gaps show as NaN.
Then summariseJoin first, then total: merged.groupby("Region")["Revenue"].sum()

Put together: pd.merge(df, stores, on="Store") adds each store's details to every order.

Practice

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

1. Build a line that joins the orders to the stores table on Store.
pd.merge(df, stores, on="Store")
2. Build a line that totals revenue for each region, from the joined table called merged.
merged.groupby("Region")["Revenue"].sum()
3. Join the orders to the stores table on Store.
pd.merge(df, stores, on="Store")
4. Find the total revenue for each manager.
pd.merge(df, stores, on="Store").groupby("Manager")["Revenue"].sum()
5. Your manager asks: which region sells more? The orders have the store but not the region, and stores has both. Show the total revenue for each region.
pd.merge(df, stores, on="Store").groupby("Region")["Revenue"].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