Section 4 · Lesson 2

Merging tables

Combine DataFrames on shared keys with merge, choose between inner and left joins, and check your row counts.

35 min 3 practice tasks
How do I merge DataFrames in pandas? by Data School on YouTube

Real data is split across tables. orders knows the customer_id but not the customer’s segment; campaigns knows the advertiser_id but not the advertiser’s industry. To answer “revenue by segment” or “budget by industry”, you first merge (join) the tables.

Keys

Tables connect through key columns:

Table Its own ID Points to
advertisers id
campaigns id advertiser_id → advertisers.id
daily_stats (campaign_id, date) campaign_id → campaigns.id
customers id
orders id customer_id → customers.id, campaign_id → campaigns.id

The basic merge

import pandas as pd

orders = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")

merged = orders.merge(customers, left_on="customer_id", right_on="id")

For each order, pandas finds the customer row whose id equals the order’s customer_id and glues the columns side by side. If the key has the same name in both tables, just write on="customer_id".

Name clashes

Both tables above have an id column (order ID and customer ID). pandas keeps both and renames them id_x and id_y, which is easy to mix up. A cleaner habit is to rename before merging:

customers = customers.rename(columns={"id": "customer_id"})
merged = orders.merge(customers, on="customer_id")

Inner vs left joins

The how= argument decides what happens to rows without a match:

how= Keeps Use it when
"inner" (default) only rows that match in both tables you only care about matched records
"left" every row of the left table; missing matches become NaN you must not lose any left rows
"right" every row of the right table rare; swap the tables and use left
"outer" every row from both reconciling two lists

This matters a lot with our orders table: 264 of the 900 orders have no campaign_id.

campaigns = pd.read_csv("campaigns.csv")
channels = campaigns[["id", "channel"]].rename(columns={"id": "campaign_id"})

orders.merge(channels, on="campaign_id")               # inner: 636 rows, unattributed orders vanish
orders.merge(channels, on="campaign_id", how="left")   # left: all 900 rows, channel is NaN for 264

If you reported total revenue from the inner join, you’d silently understate it by almost a third.

Always check your row counts

A merge can also add rows. If the right table has two rows for the same key, every matching left row is duplicated. Make it a habit:

print(len(orders), len(merged))   # should match for a left join to a lookup table

You can ask pandas to enforce it: validate="many_to_one" raises an error if the right table’s keys aren’t unique.

Finding rows without a match

indicator=True adds a _merge column saying where each row was found. It’s handy for data-quality checks:

check = orders.merge(channels, on="campaign_id", how="left", indicator=True)
check["_merge"].value_counts()      # both / left_only

Merge, then analyze

Once the columns are side by side, use everything you know:

completed = orders[orders["status"] == "completed"]
by_segment = completed.merge(customers, on="customer_id").groupby("segment")["amount"].sum()

Tip: If you know SQL, merge is a JOIN: on= is the ON clause and how="left" is a LEFT JOIN. And pandas merge doesn’t care which order the rows are in.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Add advertiser details to campaigns

Load campaigns.csv into campaigns and advertisers.csv into advertisers.

1. Rename two columns in advertisers so they don't clash with campaigns: id → advertiser_id and name → advertiser_name. 2. Merge them into campaigns_adv so each of the 40 campaigns gets its advertiser's advertiser_name, industry and country. 3. Create budget_by_industry: a Series with the total daily_budget per industry (industries as the index).

Need a hint?
  1. advertisers.rename(columns={"id": "advertiser_id", "name": "advertiser_name"}) returns the renamed table, so save it.
  2. After renaming, both tables share advertiser_id: campaigns.merge(advertisers, on="advertiser_id").
  3. Then group the merged table: .groupby("industry")["daily_budget"].sum().
Python 3
import pandas as pd

campaigns = pd.read_csv("campaigns.csv")
advertisers = pd.read_csv("advertisers.csv")

campaigns_adv = campaigns
budget_by_industry = None

print(campaigns_adv.head())
print(budget_by_industry)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

Revenue by customer segment

Load orders.csv and customers.csv. Orders link to customers through orders.customer_id → customers.id.

Create revenue_by_segment: a Series with the total amount of completed orders for each customer segment (consumer, small_business, enterprise), rounded to 2 decimals, with the segments as the index.

Need a hint?
  1. Filter to completed orders first: orders[orders["status"] == "completed"].
  2. The key columns have different names: use left_on="customer_id", right_on="id", or rename id to customer_id in customers.
  3. Then .groupby("segment")["amount"].sum().round(2).
Python 3
import pandas as pd

orders = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")

revenue_by_segment = None
print(revenue_by_segment)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Which channel drove each order?

Load orders.csv and campaigns.csv. Many orders have no campaign_id (they weren't attributed to any campaign).

1. Create orders_channel by merging orders with just the id and channel columns of campaigns, keeping every order, attributed or not. It should have exactly as many rows as orders. 2. Set unattributed to the number of rows in orders_channel whose channel is missing (an integer).

Need a hint?
  1. campaigns[["id", "channel"]].rename(columns={"id": "campaign_id"}) gives a small lookup table.
  2. how="left" keeps every row of the left table (orders), even without a match.
  3. .isna().sum() counts missing values in a column.
Python 3
import pandas as pd

orders = pd.read_csv("orders.csv")
campaigns = pd.read_csv("campaigns.csv")

orders_channel = orders
unattributed = 0

print(len(orders), len(orders_channel), unattributed)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country