25. pandas advanced — Exercises
These exercises practice every idea of the pandas advanced lesson. They use the course sales, stores, products, customers and web-traffic tables.
How to work:
- Read the task and the expected output.
- Copy the setup block below and the starter code into a script (for example
exercise.py). Replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Add the same checks to your own code. They catch the silent errors of this module: a merge that duplicates rows, a share that does not add up to 1, a refactor that changes a number.
Every exercise starts from this setup. It sets the display options and loads the five tables.
import pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])stores = pd.read_csv("data/stores.csv")products = pd.read_csv("data/products.csv")customers = pd.read_csv("data/customers.csv")web = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")Warm-up
Section titled “Warm-up”M25-W01 · Refactor a loop into groupby
Section titled “M25-W01 · Refactor a loop into groupby”Refactor: the starter adds up revenue per channel with a Python loop and a dict. Replace the loop with one groupby call. Print the result as a dict, rounded to 2 decimals.
{'online': 1519466.47, 'store': 2077057.36}totals = {}for channel, revenue in zip(sales["channel"], sales["revenue"]): totals[channel] = totals.get(channel, 0) + revenueprint(totals)# TODO: compute the same totals with groupby; print them as a dict, rounded to 2 decimalsHint 1
Group by the column that the loop uses as the dict key. Select the column that the loop adds up.
Hint 2
sales.groupby("channel")["revenue"] is the split. Add .sum() and .round(2).
Solution
channel_revenue = sales.groupby("channel")["revenue"].sum().round(2)print(channel_revenue.to_dict())assert channel_revenue.index.to_list() == ["online", "store"]assert abs(channel_revenue.sum() - sales["revenue"].sum()) < 0.01{'online': 1519466.47, 'store': 2077057.36}How it works:
groupby("channel")splits the 20,228 rows into theonlineandstoregroups.["revenue"]selects the column to aggregate, and.sum()adds it up per group.- The result is a Series indexed by the channel, sorted alphabetically.
to_dict()prints it in the same form as the loop. The second assert checks that the two groups add up to the company total.
Alternative: sales.pivot_table(index="channel", values="revenue", aggfunc="sum") gives the same numbers as a one-column DataFrame.
M25-W02 · Category summary with named aggregation
Section titled “M25-W02 · Category summary with named aggregation”Build one table per category with three columns: revenue (total), lines (number of rows) and avg_quantity (mean units per line). Sort it by revenue, largest first, and print revenue in thousands of USD with 1 decimal.
revenue lines avg_quantitycategoryElectronics 1808.1 3942 1.132Home 672.3 3265 1.242Sports 544.1 3331 1.365Clothing 314.7 4014 1.625Beauty 150.4 3109 1.766Books 106.9 2567 1.736# TODO: groupby category, then agg with three named aggregations# TODO: sort by revenue, largest first; print revenue in thousands with 1 decimalHint 1
Named aggregation has the form new_name=(source_column, function).
Hint 2
"size" counts rows. Any column works as its source, for example ("order_id", "size").
Solution
summary = ( sales.groupby("category") .agg( revenue=("revenue", "sum"), lines=("order_id", "size"), avg_quantity=("quantity", "mean"), ) .sort_values("revenue", ascending=False))print(summary.assign(revenue=summary["revenue"] / 1000).round({"revenue": 1}))assert summary.columns.to_list() == ["revenue", "lines", "avg_quantity"]assert summary["lines"].sum() == len(sales)assert summary.index[0] == "Electronics" revenue lines avg_quantitycategoryElectronics 1808.1 3942 1.132Home 672.3 3265 1.242Sports 544.1 3331 1.365Clothing 314.7 4014 1.625Beauty 150.4 3109 1.766Books 106.9 2567 1.736How it works:
- Each keyword argument of
aggcreates one column with that name. "size"counts the rows of each group;"mean"averagesquantity.sort_valuesorders the categories.assignchanges the unit only for the printout, androundwith a dict rounds only that column. Electronics has fewer lines than Clothing but by far the most revenue, because its products are expensive.
Alternative: sales.groupby("category").agg({"revenue": "sum", "order_id": "size", "quantity": "mean"}) gives the same numbers, but the columns keep their source names. You would then rename them, which named aggregation does in one step.
M25-W03 · Predict the output: agg, transform and filter
Section titled “M25-W03 · Predict the output: agg, transform and filter”Predict the output: write down what each print() shows. Then run the code and compare.
Acceptance criteria:
- Write your prediction for every line before you run the code.
- Run the code. Your prediction matches the Output in the solution, line by line.
- For each line you got wrong, you can say whether
agg,transformorfilterbehaved differently from what you expected.
df = pd.DataFrame( {"store": ["S01", "S01", "S02", "S02", "S02"], "units": [2, 4, 1, 1, 5]})g = df.groupby("store")["units"]print(g.agg("sum").to_list())print(g.transform("sum").to_list())print(len(g.agg("mean")), len(g.transform("mean")))print(df.groupby("store").filter(lambda d: d["units"].sum() > 6)["units"].to_list())print((df["units"] / g.transform("sum")).round(2).to_list())# TODO: write your prediction for each line before you run itHint 1
agg gives one value per group. transform gives one value per row.
Hint 2
Work out each store’s total first. filter keeps all rows of a group or none of them, and the test uses a strict >.
Solution
df = pd.DataFrame( {"store": ["S01", "S01", "S02", "S02", "S02"], "units": [2, 4, 1, 1, 5]})g = df.groupby("store")["units"]print(g.agg("sum").to_list())print(g.transform("sum").to_list())print(len(g.agg("mean")), len(g.transform("mean")))print(df.groupby("store").filter(lambda d: d["units"].sum() > 6)["units"].to_list())print((df["units"] / g.transform("sum")).round(2).to_list())assert g.transform("sum").index.equals(df.index)[6, 7][6, 6, 7, 7, 7]2 5[1, 1, 5][0.33, 0.67, 0.14, 0.14, 0.71]How it works:
agg("sum")returns one total per store: 6 and 7.transform("sum")repeats each store’s total on each of its rows.agg("mean")has 2 rows (one per group);transform("mean")has 5 (one per row).filterkeeps the rows of S02 only, because 6 is not greater than 6.- Dividing each row by its group total gives each row’s share of its store. The shares of a store add up to 1.
M25-W04 · A category-by-channel pivot table
Section titled “M25-W04 · A category-by-channel pivot table”Build a pivot table of total revenue with one row per category and one column per channel, plus a Total row and column. Show it in thousands of USD, rounded to 1 decimal.
channel online store TotalcategoryBeauty 63.8 86.7 150.4Books 44.6 62.3 106.9Clothing 133.2 181.5 314.7Electronics 767.1 1041.0 1808.1Home 284.1 388.2 672.3Sports 226.8 317.3 544.1Total 1519.5 2077.1 3596.5# TODO: pivot_table with index, columns, values, aggfunc, margins and margins_name# TODO: divide by 1000, round to 1 decimal and printHint 1
The default aggfunc is "mean". You want totals.
Hint 2
margins=True, margins_name="Total" adds the total row and column.
Solution
table = sales.pivot_table( index="category", columns="channel", values="revenue", aggfunc="sum", margins=True, margins_name="Total",)print(table.div(1000).round(1))assert table.shape == (7, 3)assert abs(table.loc["Total", "Total"] - sales["revenue"].sum()) < 0.01channel online store TotalcategoryBeauty 63.8 86.7 150.4Books 44.6 62.3 106.9Clothing 133.2 181.5 314.7Electronics 767.1 1041.0 1808.1Home 284.1 388.2 672.3Sports 226.8 317.3 544.1Total 1519.5 2077.1 3596.5How it works:
indexsets the rows,columnsthe columns andvaluesthe column to aggregate in each cell.aggfunc="sum"adds up the revenue. The default would show the mean line revenue.- The margins add a
Totalrow and column. The bottom-right cell is the company total. .div(1000)changes only the display unit, so the table stays short.
Alternative: sales.groupby(["category", "channel"])["revenue"].sum().unstack() gives the same cells without the margins.
M25-W05 · Melt quarterly targets to long format
Section titled “M25-W05 · Melt quarterly targets to long format”The planning team keeps revenue targets (in thousands of USD) in a wide table with one column per quarter. Melt it to long format with the columns store_id, quarter and target_k, sorted by store and quarter.
store_id quarter target_k0 S01 Q1 951 S01 Q2 1002 S01 Q3 1053 S02 Q1 624 S02 Q2 665 S02 Q3 706 S03 Q1 507 S03 Q2 528 S03 Q3 55targets = pd.DataFrame( { "store_id": ["S01", "S02", "S03"], "Q1": [95, 62, 50], "Q2": [100, 66, 52], "Q3": [105, 70, 55], })# TODO: melt to long format, sort and printHint 1
id_vars names the column that stays. The other columns become rows.
Hint 2
var_name names the column of old column names; value_name names the column of values.
Solution
targets = pd.DataFrame( { "store_id": ["S01", "S02", "S03"], "Q1": [95, 62, 50], "Q2": [100, 66, 52], "Q3": [105, 70, 55], })long = ( targets.melt(id_vars="store_id", var_name="quarter", value_name="target_k") .sort_values(["store_id", "quarter"]) .reset_index(drop=True))print(long)assert long.shape == (9, 3)assert long["target_k"].sum() == targets[["Q1", "Q2", "Q3"]].to_numpy().sum() store_id quarter target_k0 S01 Q1 951 S01 Q2 1002 S01 Q3 1053 S02 Q1 624 S02 Q2 665 S02 Q3 706 S03 Q1 507 S03 Q2 528 S03 Q3 55How it works:
meltkeepsstore_idand turns the three quarter columns into rows: 3 stores × 3 quarters = 9 rows.var_nameandvalue_namegive the two new columns clear names.meltlists all Q1 rows first, sosort_valuesgroups each store’s rows.reset_index(drop=True)renumbers them.
Alternative: targets.set_index("store_id").stack() gives the same values as a Series with a two-level index; .rename("target_k").reset_index() turns it into the same columns.
M25-W06 · Fix the bug: the region column disappears
Section titled “M25-W06 · Fix the bug: the region column disappears”Fix the bug: the starter adds the store city to each sales line and then sums revenue per region, but it raises KeyError: 'region'. Fix the merge so that the code prints the revenue per region and the list of new columns.
regionEast 993683.72North 888229.47South 891766.07West 822844.57Name: revenue, dtype: float64['city']enriched = sales.merge(stores, on="store_id")print(enriched.groupby("region")["revenue"].sum())# TODO: find out why region is missing and fix the mergeHint 1
Print enriched.columns. Which columns do sales and stores have in common?
Hint 2
Both tables have region. Merge only the columns you need from stores.
Solution
enriched = sales.merge( stores[["store_id", "city"]], on="store_id", how="left", validate="many_to_one")print(enriched.groupby("region")["revenue"].sum())print(sorted(set(enriched.columns) - set(sales.columns)))assert len(enriched) == len(sales)assert "region_x" not in enriched.columnsregionEast 993683.72North 888229.47South 891766.07West 822844.57Name: revenue, dtype: float64['city']How it works:
salesandstoresboth have aregioncolumn. The merge kept both and renamed themregion_xandregion_y, soregionno longer existed.- Selecting
["store_id", "city"]fromstoresmerges only the key and the column you need. validate="many_to_one"and the length check confirm that no row was duplicated.
Alternative: merge on both columns, on=["store_id", "region"], which also checks that each line’s region matches its store. Or keep all columns and set suffixes=("", "_store").
M25-W07 · Predict the output: rolling, expanding and shift
Section titled “M25-W07 · Predict the output: rolling, expanding and shift”Predict the output: a sensor sends 6 values, and one is missing. Write down what each line prints. Then run the code and compare.
Acceptance criteria:
- Write your prediction for every line before you run the code.
- Run the code. Your prediction matches the Output in the solution, line by line.
- You can explain why one line has three
nanvalues and another has none.
s = pd.Series([10.0, 20.0, None, 40.0, 50.0, 60.0])print(s.rolling(2).mean().to_list())print(s.rolling(2, min_periods=1).mean().to_list())print(s.expanding().sum().to_list())print(s.shift(1).to_list())# TODO: write your prediction for each line before you run itHint 1
rolling(2) needs 2 non-missing values in its window by default. A window that contains the missing value has only 1.
Hint 2
expanding() needs only 1 value, and its sum skips the missing value.
Solution
s = pd.Series([10.0, 20.0, None, 40.0, 50.0, 60.0])print(s.rolling(2).mean().to_list())print(s.rolling(2, min_periods=1).mean().to_list())print(s.expanding().sum().to_list())print(s.shift(1).to_list())assert s.rolling(2).mean().isna().sum() == 3[nan, 15.0, nan, nan, 45.0, 55.0][10.0, 15.0, 20.0, 40.0, 45.0, 55.0][10.0, 30.0, 30.0, 70.0, 120.0, 180.0][nan, 10.0, 20.0, nan, 40.0, 50.0]How it works:
rolling(2).mean(): the first window has 1 value, and the windows at positions 2 and 3 contain the missing value. These three arenan.min_periods=1computes from whatever values exist: the window (20, NaN) gives 20 and (NaN, 40) gives 40.expanding().sum()is a running total that skips NaN, so it stays at 30 at position 2.shift(1)moves every value down one row. The first row becomesnan, and the gap moves to position 3.
M25-W08 · Accessors: weekdays and product names
Section titled “M25-W08 · Accessors: weekdays and product names”Use .dt to count the order lines per weekday, Monday first, with the weekday names as the index. Then use .str to list the products whose name contains a digit.
order_dateMonday 2494Tuesday 2387Wednesday 2506Thursday 2574Friday 3301Saturday 3699Sunday 3267Name: count, dtype: int642 55-inch 4K Smart TV3 14-inch Ultrabook Laptop4 Smartwatch Series 513 Running Socks 3-Pack19 2-Person Camping Tent29 Mineral Sunscreen SPF 50Name: product, dtype: str# TODO: count lines per weekday with .dt.day_name(), Monday first# TODO: list the product names that contain a digit with .str.containsHint 1
value_counts() sorts by count. reindex([...]) puts the index in the order you give.
Hint 2
The regular expression r"\d" matches any digit.
Solution
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]per_day = sales["order_date"].dt.day_name().value_counts().reindex(week)print(per_day)names = products["product"]with_digit = names[names.str.contains(r"\d")]print(with_digit)assert per_day.sum() == len(sales)assert len(with_digit) == 6order_dateMonday 2494Tuesday 2387Wednesday 2506Thursday 2574Friday 3301Saturday 3699Sunday 3267Name: count, dtype: int642 55-inch 4K Smart TV3 14-inch Ultrabook Laptop4 Smartwatch Series 513 Running Socks 3-Pack19 2-Person Camping Tent29 Mineral Sunscreen SPF 50Name: product, dtype: strHow it works:
.dt.day_name()turns each date into its weekday name.value_counts()counts them.reindex(week)orders the counts Monday to Sunday. Saturday has the most lines..str.contains(r"\d")returns a boolean mask:Truewhere the name contains a digit. The mask selects six products.
Alternative: group by .dt.day_of_week (Monday = 0), which sorts numerically by itself: sales.groupby(sales["order_date"].dt.day_of_week).size().
M25-W09 · Parse sizes from product names
Section titled “M25-W09 · Parse sizes from product names”Some product names carry a size, such as 55-inch or 3-Pack. Use .str.extract with two named groups, size and unit, to pull them out, and .str.split(expand=True) to get the first word of each name as first_word. Print the products that have a size, with the columns product, first_word, size and unit, and size as an integer.
product first_word size unit 55-inch 4K Smart TV 55-inch 55 inch14-inch Ultrabook Laptop 14-inch 14 inch Running Socks 3-Pack Running 3 Pack 2-Person Camping Tent 2-Person 2 Personnames = products["product"]# TODO: parts = names.str.extract(...) with named groups size and unit# TODO: first_word = the first column of a split into at most 2 parts# TODO: combine, keep the rows that have a size, convert size to int and printHint 1
A named group has the form (?P<size>\d+). str.extract uses the group names as column names.
Hint 2
names.str.split(" ", n=1, expand=True)[0] is the first word. Rows without a size have NaN in size, so dropna(subset=["size"]) removes them.
Solution
names = products["product"]parts = names.str.extract(r"(?P<size>\d+)-(?P<unit>inch|Pack|Person)")first_word = names.str.split(" ", n=1, expand=True)[0].rename("first_word")sized = ( pd.concat([names, first_word, parts], axis=1) .dropna(subset=["size"]) .astype({"size": "int64"}))print(sized.to_string(index=False))assert sized.columns.to_list() == ["product", "first_word", "size", "unit"]assert sized["size"].sum() == 55 + 14 + 3 + 2 product first_word size unit 55-inch 4K Smart TV 55-inch 55 inch14-inch Ultrabook Laptop 14-inch 14 inch Running Socks 3-Pack Running 3 Pack 2-Person Camping Tent 2-Person 2 PersonHow it works:
str.extractreturns one column per capturing group. The named groupssizeandunitbecome the column names. Rows where the pattern does not match get NaN.str.split(" ", n=1, expand=True)splits each name at the first space into two columns. Column0is the first word.pd.concat(axis=1)puts the three pieces side by side, aligned on the product index.dropnakeeps the four sized products, andastypeturns the size text into numbers.
Alternative: names.str.extract(r"^(\S+)") gets the first word with a regular expression instead of a split.
M25-C01 · Each category’s top product by share
Section titled “M25-C01 · Each category’s top product by share”For each product, compute its share of its category’s revenue. Then show the top product of each category with its revenue and share, one row per category, sorted by category.
category product revenue share0 Beauty Electric Toothbrush 43618.57 0.2907 Books Statistics Made Simple 31270.35 0.29214 Clothing Waterproof Rain Jacket 104660.50 0.33315 Electronics 14-inch Ultrabook Laptop 665328.45 0.36823 Home Espresso Machine 197987.70 0.29426 Sports Adjustable Dumbbells 165084.30 0.303prod = sales.groupby(["category", "product"], as_index=False)["revenue"].sum()# TODO: add a share column: revenue / the category total (use transform)# TODO: keep the row with the largest share in each category and print itHint 1
prod.groupby("category")["revenue"].transform("sum") gives the category total on every product row.
Hint 2
Sort by share, largest first. Then groupby("category").head(1) keeps the first row of each category.
Solution
prod = sales.groupby(["category", "product"], as_index=False)["revenue"].sum()prod["share"] = prod["revenue"] / prod.groupby("category")["revenue"].transform("sum")top = ( prod.sort_values("share", ascending=False) .groupby("category") .head(1) .sort_values("category"))print(top)assert (prod.groupby("category")["share"].sum() - 1).abs().max() < 1e-9assert len(top) == 6 category product revenue share0 Beauty Electric Toothbrush 43618.57 0.2907 Books Statistics Made Simple 31270.35 0.29214 Clothing Waterproof Rain Jacket 104660.50 0.33315 Electronics 14-inch Ultrabook Laptop 665328.45 0.36823 Home Espresso Machine 197987.70 0.29426 Sports Adjustable Dumbbells 165084.30 0.303How it works:
- The first groupby gives one row per product with its total revenue.
transform("sum")puts each category’s total on each of its product rows, so the division gives a share. The first assert checks that the shares of each category add up to 1.- After sorting by share,
groupby("category").head(1)keeps the first, largest row of each category. - The laptop takes 36.8% of Electronics revenue. In every category, the top product brings 29% to 37% of the revenue.
Alternative: prod.loc[prod.groupby("category")["share"].idxmax()] selects the row label of each category’s maximum directly.
M25-C02 · Unusual monthly charges within each plan
Section titled “M25-C02 · Unusual monthly charges within each plan”Customers on the premium plan pay more than basic customers, so a high charge means something different on each plan. Compute the z-score of monthly_charges within each plan. Print, per plan, the number of customers, the largest z-score and the number of customers with a z-score above 2.5.
customers max_z above_2_5planbasic 2028 5.699 54premium 990 5.728 20standard 1982 4.777 49by_plan = customers.groupby("plan")["monthly_charges"]# TODO: z = (charge - plan mean) / plan std, with transform# TODO: per plan: customers, max_z, above_2_5 (named aggregation)Hint 1
by_plan.transform("mean") and by_plan.transform("std") give the plan’s mean and standard deviation on every row.
Hint 2
Add the z-score and a boolean column z > 2.5 with assign. The sum of a boolean column counts the True values.
Solution
by_plan = customers.groupby("plan")["monthly_charges"]charges = customers["monthly_charges"]z = (charges - by_plan.transform("mean")) / by_plan.transform("std")report = ( customers.assign(z=z, high=z > 2.5) .groupby("plan") .agg( customers=("customer_id", "size"), max_z=("z", "max"), above_2_5=("high", "sum"), ))print(report)check = customers.assign(z=z).groupby("plan")["z"].agg(["mean", "std"])assert check["mean"].abs().max() < 1e-9assert (check["std"] - 1).abs().max() < 1e-9 customers max_z above_2_5planbasic 2028 5.699 54premium 990 5.728 20standard 1982 4.777 49How it works:
transformgives each customer the mean and standard deviation of their own plan.- The z-score measures the distance from the plan’s mean in plan standard deviations. Within every plan, it has mean 0 and standard deviation 1, which the asserts check.
- The boolean column
highis summed per plan, which counts the customers above 2.5. - Each plan has a few customers more than 5 standard deviations above its mean. Module 26 decides whether such values are errors or real.
Alternative: by_plan.transform(lambda s: (s - s.mean()) / s.std()) computes the z-score in one call, but it runs a Python function per group, which is slower on many groups.
M25-C03 · Refactor filter into a transform mask
Section titled “M25-C03 · Refactor filter into a transform mask”Refactor: the starter keeps the sales lines of loyal customers (10 or more distinct orders) with filter, which calls a Python function for each of the 3,254 customers. Rewrite it with a transform mask. Print the number of loyal customers, their number of lines and their share of total revenue, and check that both versions select the same rows.
412 8142 0.397by_customer = sales.groupby("customer_id")loyal_slow = by_customer.filter(lambda g: g["order_id"].nunique() >= 10)# TODO: compute orders per customer on every row with transform("nunique")# TODO: select the loyal rows with a boolean mask# TODO: print customers, lines and revenue share; compare with loyal_slowHint 1
sales.groupby("customer_id")["order_id"].transform("nunique") gives each line its customer’s number of orders.
Hint 2
loyal.index.equals(loyal_slow.index) checks that both versions kept the same rows in the same order.
Solution
by_customer = sales.groupby("customer_id")loyal_slow = by_customer.filter(lambda g: g["order_id"].nunique() >= 10)orders_per_customer = by_customer["order_id"].transform("nunique")loyal = sales[orders_per_customer >= 10]share = loyal["revenue"].sum() / sales["revenue"].sum()print(loyal["customer_id"].nunique(), len(loyal), round(share, 3))assert loyal.index.equals(loyal_slow.index)assert loyal.groupby("customer_id")["order_id"].nunique().min() >= 10412 8142 0.397How it works:
transform("nunique")counts each customer’s distinct orders and repeats the count on every line of that customer.- The comparison
>= 10turns it into a mask with one value per line, andsales[mask]keeps the loyal lines. - Both versions keep the original row order, so
index.equalsconfirms the refactor. - 412 customers, 13% of the 3,254 buyers, bring about 40% of the revenue.
Alternative: compute the set of loyal ids first: ids = orders.index[orders >= 10] with orders = sales.groupby("customer_id")["order_id"].nunique(), then sales[sales["customer_id"].isin(ids)].
M25-C04 · Interpret empty age bands
Section titled “M25-C04 · Interpret empty age bands”Interpret a result: put the customers into the age bands under 18, 18-30, 31-45, 46-60, 61-80 and over 80 with pd.cut. Report the number of customers and the churn rate per band with observed=False. Then explain in one sentence each: why two bands have 0 customers, and why their churn rate is NaN and not 0.
customers churn_rateageunder 18 0 NaN18-30 948 0.27531-45 2025 0.16546-60 1617 0.15561-80 410 0.285over 80 0 NaN4bins = [0, 17, 30, 45, 60, 80, 120]labels = ["under 18", "18-30", "31-45", "46-60", "61-80", "over 80"]# TODO: age_band = pd.cut(...)# TODO: groupby the band with observed=False: customers (size), churn_rate (mean of churned)Hint 1
pd.cut(customers["age"], bins=bins, labels=labels) returns a categorical with all six labels as categories.
Hint 2
What is the mean of zero values? What is their count?
Solution
bins = [0, 17, 30, 45, 60, 80, 120]labels = ["under 18", "18-30", "31-45", "46-60", "61-80", "over 80"]age_band = pd.cut(customers["age"], bins=bins, labels=labels)bands = customers.groupby(age_band, observed=False).agg( customers=("customer_id", "size"), churn_rate=("churned", "mean"))print(bands)print(len(customers.groupby(age_band)["churned"].mean()))assert bands["customers"].sum() == len(customers)assert bands.loc["under 18", "customers"] == 0assert pd.isna(bands.loc["over 80", "churn_rate"]) customers churn_rateageunder 18 0 NaN18-30 948 0.27531-45 2025 0.16546-60 1617 0.15561-80 410 0.285over 80 0 NaN4How it works:
pd.cutputs each age into a bin.(0, 17]means “above 0, up to 17”, so the labelunder 18is right.- Ages run from 18 to 80, so the first and the last band have no customers.
observed=Falsekeeps them, with a size of 0. - The churn rate is a mean. The mean of zero values is undefined, so pandas shows
NaN. A rate of 0 would claim “nobody churned”, which is a different statement from “nobody to measure”. - With the pandas 3 default
observed=True, the empty bands disappear: the last line shows 4 groups.
M25-C05 · Choose a method: churn by contract and payment
Section titled “M25-C05 · Choose a method: churn by contract and payment”Choose a method and justify it: build a table of churn rates with one row per contract and one column per payment_method, rounded to 3 decimals. The candidates are pivot, pivot_table and crosstab. Pick one, write the table and give one sentence on why the other two fit less well.
payment_method bank_transfer credit_card electronic_check paypalcontractmonth-to-month 0.273 0.250 0.370 0.265one-year 0.088 0.065 0.117 0.073two-year 0.013 0.019 0.064 0.023# TODO: churn rate (mean of churned) per contract x payment_method, rounded to 3 decimals# TODO: in a comment, justify the method you choseHint 1
Each (contract, payment_method) pair occurs hundreds of times. The cell value is an aggregate: the mean of churned.
Hint 2
churned is 0 or 1, so its mean is the churn rate.
Solution
churn = customers.pivot_table( index="contract", columns="payment_method", values="churned", aggfunc="mean").round(3)print(churn)# pivot cannot aggregate: each pair occurs many times, so it raises ValueError.# crosstab counts by default; it needs values= and aggfunc= to compute a mean,# so pivot_table states the intent (aggregate a value) most directly.assert churn.shape == (3, 4)assert churn.loc["month-to-month"].min() > churn.loc["two-year"].max()payment_method bank_transfer credit_card electronic_check paypalcontractmonth-to-month 0.273 0.250 0.370 0.265one-year 0.088 0.065 0.117 0.073two-year 0.013 0.019 0.064 0.023How it works:
pivot_tablegroups by the two keys and computes the mean ofchurnedin each cell.- Every month-to-month cell is higher than every two-year cell, which the last assert checks. The contract matters more than the payment method.
- Electronic check has the highest churn in every contract type.
Alternative: pd.crosstab(customers["contract"], customers["payment_method"], values=customers["churned"], aggfunc="mean") gives the same table. customers.groupby(["contract", "payment_method"])["churned"].mean().unstack() does too, and lets you add more aggregations first.
M25-C06 · Interpret the margins of a mean pivot table
Section titled “M25-C06 · Interpret the margins of a mean pivot table”Interpret a result: build a pivot table of the mean line revenue per region (rows) and channel (columns) with margins. The All value for East is not the average of its two cells. Show this, and reproduce the All value from the cells and the number of lines per cell.
channel online store AllregionEast 187.234 181.902 184.152North 176.161 180.914 178.862South 180.690 168.210 173.360West 170.088 177.194 174.258All 178.866 177.027 177.799184.568 184.152# TODO: pivot_table of mean revenue, region x channel, margins=True# TODO: print it, the simple average of the two East cells, and the line-weighted averageHint 1
The margin is computed from all East lines together, not from the two cell means.
Hint 2
A weighted average multiplies each cell mean by its number of lines, sums the products and divides by the total number of lines. pd.crosstab gives the line counts.
Solution
means = sales.pivot_table( index="region", columns="channel", values="revenue", aggfunc="mean", margins=True)print(means)east = means.loc["East", ["online", "store"]]counts = pd.crosstab(sales["region"], sales["channel"]).loc["East"]simple = east.mean()weighted = (east * counts).sum() / counts.sum()print(round(simple, 3), round(weighted, 3))assert abs(weighted - means.loc["East", "All"]) < 1e-9assert abs(simple - means.loc["East", "All"]) > 0.1channel online store AllregionEast 187.234 181.902 184.152North 176.161 180.914 178.862South 180.690 168.210 173.360West 170.088 177.194 174.258All 178.866 177.027 177.799184.568 184.152How it works:
margins=Trueapplies the sameaggfuncto all the lines of a row or a column. For a mean, theAllcell is the mean of all East lines.- East has more store lines (3,119) than online lines (2,277), so the store mean counts more. The simple average of the two cells gives each cell the same weight.
- Weighting each cell by its line count reproduces the margin exactly. This is a general rule: a mean of means is not the overall mean unless the groups have the same size.
M25-C07 · How often do customers buy in their own region?
Section titled “M25-C07 · How often do customers buy in their own region?”Merge each sales line with its customer’s region. Name the two region columns region_store and region_customer. Print the share of lines where they are equal, overall and per channel.
0.889channelonline 0.883store 0.893dtype: float64# TODO: merge sales with customers[["customer_id", "region"]] on customer_id# with suffixes and validate="many_to_one"# TODO: same_region = region_store == region_customer# TODO: print the overall share and the share per channelHint 1
suffixes=("_store", "_customer") renames the two region columns. The first suffix goes to the left table.
Hint 2
The mean of a boolean column is the share of True values. Group it by channel.
Solution
lines = sales.merge( customers[["customer_id", "region"]], on="customer_id", how="left", suffixes=("_store", "_customer"), validate="many_to_one",)same = lines["region_store"] == lines["region_customer"]print(round(same.mean(), 3))print(same.groupby(lines["channel"]).mean().round(3))assert len(lines) == len(sales)assert lines["region_customer"].notna().all()0.889channelonline 0.883store 0.893dtype: float64How it works:
- The merge is many-to-one: many lines per customer, one row per customer.
validatechecks it, and the length stays 20,228. - Both tables have
region, so the suffixes name them. Withoutsuffixes, you would getregion_xandregion_y. - The comparison gives a boolean Series. Its mean is the share of matching lines: 88.9%, as in the data dictionary.
same.groupby(lines["channel"])groups a Series by another Series of the same length. The two channels differ by only one percentage point: 88.3% online and 89.3% in store.
Alternative: lines.assign(same=same).groupby("channel")["same"].mean() gives the same per-channel shares from a column.
M25-C08 · Fix the bug: a cost update doubles a product
Section titled “M25-C08 · Fix the bug: a cost update doubles a product”Fix the bug: the supplier lowered the unit cost of the TV (P003) to 830.00. The starter appends the new cost to the cost table and merges. Profit and line count are now wrong. Find the cause, fix it so the newest cost wins, and add a check that would have caught the bug.
20228 1767695.83[830.0]price_fix = pd.DataFrame({"product_id": ["P003"], "unit_cost": [830.0]})costs = pd.concat([products[["product_id", "unit_cost"]], price_fix])lines = sales.merge(costs, on="product_id")profit = (lines["revenue"] - lines["unit_cost"] * lines["quantity"]).sum()print(len(lines), round(profit, 2))# TODO: why are there more than 20,228 lines? Fix costs and validate the mergeHint 1
Print costs["product_id"].value_counts().head(2). How many rows does P003 have?
Hint 2
drop_duplicates("product_id", keep="last") keeps the row that came last, which is the update.
Solution
price_fix = pd.DataFrame({"product_id": ["P003"], "unit_cost": [830.0]})costs = pd.concat([products[["product_id", "unit_cost"]], price_fix])costs = costs.drop_duplicates("product_id", keep="last")lines = sales.merge(costs, on="product_id", how="left", validate="many_to_one")profit = (lines["revenue"] - lines["unit_cost"] * lines["quantity"]).sum()print(len(lines), round(profit, 2))print(costs.loc[costs["product_id"] == "P003", "unit_cost"].to_list())assert len(lines) == len(sales)assert costs["product_id"].is_unique20228 1767695.83[830.0]How it works:
- After
concat, P003 appears twice incosts. The merge matched each of its 427 lines twice, so the buggy code had 20,655 lines and counted every TV sale twice. drop_duplicates(..., keep="last")keeps one row per product, the update.validate="many_to_one"raises aMergeErrorif the right table ever has a duplicate key again. The length assert is a second safety net.- The new cost raises profit by 15 USD per TV unit sold.
Alternative: update the cost in place instead of appending: costs = products.set_index("product_id")["unit_cost"].copy(), then costs.loc["P003"] = 830.0, and sales["product_id"].map(costs) to look up the cost per line.
M25-C09 · Year-over-year table with concat
Section titled “M25-C09 · Year-over-year table with concat”Compute the revenue per region for 2023 and for 2024 as two separate Series. Combine them side by side with pd.concat, with the column names 2023 and 2024, and add a growth column. Show the revenue in thousands of USD.
2023 2024 growthregionEast 448.919 544.765 0.214North 410.500 477.729 0.164South 409.501 482.265 0.178West 376.670 446.175 0.185year = sales["order_date"].dt.year# TODO: rev_2023 and rev_2024: revenue per region for each year# TODO: concat side by side with keys, add growth, print in thousandsHint 1
pd.concat([a, b], axis=1) aligns the two Series on their index (the regions) and puts them side by side.
Hint 2
keys=["2023", "2024"] names the columns.
Solution
year = sales["order_date"].dt.yearrev_2023 = sales[year == 2023].groupby("region")["revenue"].sum()rev_2024 = sales[year == 2024].groupby("region")["revenue"].sum()yoy = pd.concat([rev_2023, rev_2024], axis=1, keys=["2023", "2024"]).div(1000)yoy["growth"] = yoy["2024"] / yoy["2023"] - 1print(yoy.round(3))assert yoy.shape == (4, 3)assert yoy["growth"].between(0.15, 0.22).all() 2023 2024 growthregionEast 448.919 544.765 0.214North 410.500 477.729 0.164South 409.501 482.265 0.178West 376.670 446.175 0.185How it works:
- Each groupby returns a Series indexed by region.
pd.concat(..., axis=1)aligns the two Series on their index. A region missing in one year would get NaN instead of a shifted value.keysnames the columns. The growth is a ratio, so dividing both years by 1000 does not change it.- East grew fastest (21.4%), North slowest (16.4%).
Alternative: one pivot_table(index="region", columns=year, values="revenue", aggfunc="sum") builds both columns in one step. concat is the tool when the two Series come from different sources, such as two files.
M25-C10 · Online growth per category with xs
Section titled “M25-C10 · Online growth per category with xs”Group revenue by channel, category and year into a Series with a three-level MultiIndex. Use xs to select the online channel, unstack the years and add the growth from 2023 to 2024. Sort by growth, largest first, and show the revenue in thousands.
year 2023 2024 growthcategoryHome 102.209 181.857 0.779Sports 83.375 143.397 0.720Clothing 53.324 79.829 0.497Beauty 25.764 37.994 0.475Books 18.535 26.109 0.409Electronics 339.646 427.427 0.258year = sales["order_date"].dt.year.rename("year")# TODO: rev = revenue per channel, category, year# TODO: online = rev.xs(...), unstack the years, add growth, sort and printHint 1
sales.groupby(["channel", "category", year]) groups by two columns and one Series. The Series name becomes the level name.
Hint 2
rev.xs("online", level="channel") drops the channel level. unstack("year") moves the years into columns.
Solution
year = sales["order_date"].dt.year.rename("year")rev = sales.groupby(["channel", "category", year])["revenue"].sum().div(1000)online = rev.xs("online", level="channel").unstack("year")online["growth"] = online[2024] / online[2023] - 1online = online.sort_values("growth", ascending=False)print(online.round(3))assert rev.index.names == ["channel", "category", "year"]assert online.shape == (6, 3)assert (online["growth"] > 0.25).all()year 2023 2024 growthcategoryHome 102.209 181.857 0.779Sports 83.375 143.397 0.720Clothing 53.324 79.829 0.497Beauty 25.764 37.994 0.475Books 18.535 26.109 0.409Electronics 339.646 427.427 0.258How it works:
- The groupby on three keys gives a Series with the levels
channel,categoryandyear. The Seriesyearwas renamed, so its level has a clear name. xs("online", level="channel")keeps the online rows and drops that level.unstack("year")turns the year level into columns, so the growth is one division.- Online revenue grew by more than 25% in every category and by more than 70% in Home and Sports. The company total grew by 18.6%, so the online share is rising.
Alternative: rev.loc["online"] gives the same rows, because channel is the outermost level. xs also works for inner levels, such as rev.xs("Books", level="category").
M25-C11 · Regional shares of each year with unstack and stack
Section titled “M25-C11 · Regional shares of each year with unstack and stack”Compute each region’s share of the year’s revenue for 2023 and 2024. Start from a long Series indexed by (region, year), unstack the years, divide each column by its total, and stack the result back to a long Series. Print the wide table and the first four rows of the long one.
year 2023 2024regionEast 0.273 0.279North 0.249 0.245South 0.249 0.247West 0.229 0.229region yearEast 2023 0.273 2024 0.279North 2023 0.249 2024 0.245dtype: float64year = sales["order_date"].dt.year.rename("year")long_rev = sales.groupby(["region", year])["revenue"].sum()# TODO: wide = unstack the years; shares = wide / wide.sum()# TODO: long_share = shares.stack(); print bothHint 1
wide.sum() sums each column. Dividing a DataFrame by a Series aligns the Series index with the columns.
Hint 2
stack() moves the columns back into the innermost index level.
Solution
year = sales["order_date"].dt.year.rename("year")long_rev = sales.groupby(["region", year])["revenue"].sum()wide = long_rev.unstack("year")shares = wide / wide.sum()long_share = shares.stack()print(shares.round(3))print(long_share.head(4).round(3))assert (shares.sum() - 1).abs().max() < 1e-9assert long_share.index.equals(long_rev.index)year 2023 2024regionEast 0.273 0.279North 0.249 0.245South 0.249 0.247West 0.229 0.229region yearEast 2023 0.273 2024 0.279North 2023 0.249 2024 0.245dtype: float64How it works:
unstack("year")gives a 4 × 2 table: regions in rows, years in columns.wide.sum()is a Series with one total per year.wide / wide.sum()divides each column by its own total, because pandas aligns the Series index with the column labels.stack()turns the table back into a long Series with the same (region, year) index as the input, which the second assert checks.- The shares barely move between the years: East stays the largest region at about 27–28%.
Alternative: long_rev / long_rev.groupby(level="year").transform("sum") computes the long shares directly, without reshaping.
M25-C12 · When does each category peak?
Section titled “M25-C12 · When does each category peak?”Build a wide table of daily units per category (dates in rows, categories in columns, 0 for days without sales). Compute the 28-day rolling mean of each column. For each category, print the last day of its best 28-day window and the mean daily units in that window.
(731, 6) peak_end peak_unitscategorySports 2024-08-01 10.357Clothing 2024-12-20 20.929Electronics 2024-12-21 17.214Beauty 2024-12-23 18.286Home 2024-12-23 12.607Books 2024-12-26 14.000# TODO: a wide table of units: one row per day, one column per category, 0 for no sales# TODO: a 28-day moving average of every column# TODO: per category: the last day of the best window and its mean daily unitsHint 1
rolling on a DataFrame works column by column.
Hint 2
roll.idxmax() returns the index label (the date) of each column’s maximum. roll.max() returns the values.
Solution
daily_units = sales.pivot_table( index="order_date", columns="category", values="quantity", aggfunc="sum", fill_value=0,)roll = daily_units.rolling(28).mean()peaks = pd.DataFrame({"peak_end": roll.idxmax(), "peak_units": roll.max()})print(daily_units.shape)print(peaks.sort_values("peak_end"))assert daily_units.shape == (731, 6)assert peaks.loc["Sports", "peak_end"].month in (6, 7, 8)(731, 6) peak_end peak_unitscategorySports 2024-08-01 10.357Clothing 2024-12-20 20.929Electronics 2024-12-21 17.214Beauty 2024-12-23 18.286Home 2024-12-23 12.607Books 2024-12-26 14.000How it works:
- The pivot table has one row per day and one column per category.
fill_value=0is right here: a day with no Books lines sold 0 books. rolling(28).mean()smooths each column separately.idxmax()gives the date where each 28-day mean is highest; that date is the last day of the window.- Sports peaks in summer. Every other category peaks in December 2024, in the holiday season at the end of a growing year.
Alternative: stay in long format: sales.groupby(["category", "order_date"])["quantity"].sum() and then .groupby(level="category").rolling(28).mean(). The wide table is simpler here, because every category has the same dates.
M25-C13 · Refactor a quarterly report into a chain
Section titled “M25-C13 · Refactor a quarterly report into a chain”Refactor: the starter computes the online share of Electronics revenue per quarter with temporary variables. Rewrite it as one method chain with query, assign, groupby and pipe, and prove with pd.testing.assert_frame_equal that the result is identical.
revenue online_revenue online_sharequarter2023Q1 139713.09 45157.67 0.3232023Q2 191336.14 67495.98 0.3532023Q3 216836.51 84597.50 0.3902023Q4 320297.66 142394.82 0.4452024Q1 184787.17 65308.66 0.3532024Q2 169101.57 66840.01 0.3952024Q3 193670.32 90354.22 0.4672024Q4 392365.71 204923.62 0.522identical: Truedf = sales[sales["category"] == "Electronics"]df = df.assign(quarter=df["order_date"].dt.to_period("Q"))df = df.assign(online_revenue=df["revenue"].where(df["channel"] == "online", 0))q = df.groupby("quarter")[["revenue", "online_revenue"]].sum()q["online_share"] = q["online_revenue"] / q["revenue"]before = q.round(3)print(before)
def add_online_share(table: pd.DataFrame) -> pd.DataFrame: return table.assign(online_share=table["online_revenue"] / table["revenue"])
# TODO: after = (sales.query(...).assign(...).assign(...).groupby(...)...)# TODO: pd.testing.assert_frame_equal(before, after)Hint 1
Inside a chain, assign needs a lambda to see the current frame: assign(quarter=lambda d: d["order_date"].dt.to_period("Q")).
Hint 2
.pipe(add_online_share) calls the function with the grouped table. End with .round(3).
Solution
df = sales[sales["category"] == "Electronics"]df = df.assign(quarter=df["order_date"].dt.to_period("Q"))df = df.assign(online_revenue=df["revenue"].where(df["channel"] == "online", 0))q = df.groupby("quarter")[["revenue", "online_revenue"]].sum()q["online_share"] = q["online_revenue"] / q["revenue"]before = q.round(3)print(before)
def add_online_share(table: pd.DataFrame) -> pd.DataFrame: return table.assign(online_share=table["online_revenue"] / table["revenue"])
after = ( sales .query("category == 'Electronics'") .assign( quarter=lambda d: d["order_date"].dt.to_period("Q"), online_revenue=lambda d: d["revenue"].where(d["channel"] == "online", 0), ) .groupby("quarter")[["revenue", "online_revenue"]] .sum() .pipe(add_online_share) .round(3))pd.testing.assert_frame_equal(before, after)print("identical:", before.equals(after))assert after["online_share"].iloc[-1] > after["online_share"].iloc[0] revenue online_revenue online_sharequarter2023Q1 139713.09 45157.67 0.3232023Q2 191336.14 67495.98 0.3532023Q3 216836.51 84597.50 0.3902023Q4 320297.66 142394.82 0.4452024Q1 184787.17 65308.66 0.3532024Q2 169101.57 66840.01 0.3952024Q3 193670.32 90354.22 0.4672024Q4 392365.71 204923.62 0.522identical: TrueHow it works:
queryreplaces the boolean mask. The string reads like the condition.- One
assigncan create several columns. With lambdas, each sees the frame as it enters this step. pipe(add_online_share)calls the named function with the grouped table. A named step documents itself.assert_frame_equalpasses, so the refactor kept every value, dtype and label. The online share of Electronics rose from 32.3% in 2023Q1 to 52.2% in 2024Q4.
Alternative: use named aggregation instead of the helper column: .groupby("quarter").agg(revenue=("revenue", "sum"), online_revenue=("online_revenue", "sum")) after the assign.
M25-C14 · Compare rolling and ewm at a campaign start
Section titled “M25-C14 · Compare rolling and ewm at a campaign start”The campaign of 2024-04-08 makes visits jump from about 4,600 to 18,385 in one day. Compare two smoothers of web["visits"] from 2024-04-05 to 2024-04-18: a 7-day rolling mean and an EWMA with span=7, adjust=False. Print the three columns rounded to whole visits, then print the date on which each column peaks.
visits roll7 ewm7date2024-04-05 4556.0 4926.0 4917.02024-04-06 4065.0 4874.0 4704.02024-04-07 4605.0 4871.0 4679.02024-04-08 18385.0 6763.0 8106.02024-04-09 15901.0 8222.0 10055.02024-04-10 10673.0 8977.0 10209.02024-04-11 9342.0 9647.0 9992.02024-04-12 6809.0 9969.0 9197.02024-04-13 5259.0 10139.0 8212.02024-04-14 5585.0 10279.0 7555.02024-04-15 5691.0 8466.0 7089.02024-04-16 5019.0 6911.0 6572.02024-04-17 5115.0 6117.0 6208.02024-04-18 5307.0 5541.0 5982.0{'visits': '2024-04-08', 'roll7': '2024-04-14', 'ewm7': '2024-04-10'}visits = web["visits"]# TODO: a DataFrame with visits, roll7 and ewm7# TODO: print the window 2024-04-05 to 2024-04-18, then the date of each column's peakHint 1
Compute both smoothers on the full series first, then select the dates with loc. A rolling mean computed after the selection would have NaN for its first 6 rows.
Hint 2
DataFrame.idxmax() returns the index label of each column’s maximum.
Solution
visits = web["visits"]smooth = pd.DataFrame( { "visits": visits, "roll7": visits.rolling(7).mean(), "ewm7": visits.ewm(span=7, adjust=False).mean(), })window = smooth.loc["2024-04-05":"2024-04-18"]print(window.round(0))peaks = window.idxmax()print(peaks.dt.strftime("%Y-%m-%d").to_dict())assert peaks["ewm7"] < peaks["roll7"]assert window["ewm7"].iloc[-1] > window["roll7"].iloc[-1] visits roll7 ewm7date2024-04-05 4556.0 4926.0 4917.02024-04-06 4065.0 4874.0 4704.02024-04-07 4605.0 4871.0 4679.02024-04-08 18385.0 6763.0 8106.02024-04-09 15901.0 8222.0 10055.02024-04-10 10673.0 8977.0 10209.02024-04-11 9342.0 9647.0 9992.02024-04-12 6809.0 9969.0 9197.02024-04-13 5259.0 10139.0 8212.02024-04-14 5585.0 10279.0 7555.02024-04-15 5691.0 8466.0 7089.02024-04-16 5019.0 6911.0 6572.02024-04-17 5115.0 6117.0 6208.02024-04-18 5307.0 5541.0 5982.0{'visits': '2024-04-08', 'roll7': '2024-04-14', 'ewm7': '2024-04-10'}How it works:
- Both smoothers run on the whole series, so the first rows of the window already have values.
- The rolling mean gives each of the last 7 days the same weight. It keeps rising until 2024-04-14, the last day whose window still contains the spike day. On 2024-04-15 the spike leaves the window, and the mean drops by about 1,800 at once.
- The EWMA gives the newest day a weight of 0.25 and older days less. It peaks two days after the spike and then falls smoothly, with no jump when the spike gets 7 days old.
- Choose the EWMA when recent days should count most and you want no jumps. Choose the rolling mean when every day of the window should count the same, for example for a weekly total.
Alternative: visits.rolling(7, center=True).mean() lines the peak up with the spike, but it uses future days, so it only suits a chart of past data.
M25-C15 · Find lapsed buyers with indicator and join
Section titled “M25-C15 · Find lapsed buyers with indicator and join”A lapsed buyer ordered in 2023 but not in 2024. Find them with an anti-join: a left merge of the 2023 buyers with the 2024 buyers, with indicator=True. Then add each lapsed buyer’s region, plan and churned from customers with join on the index. Print the _merge counts and, per region, the number of lapsed buyers and their churn rate.
{'both': 1524, 'left_only': 399, 'right_only': 0} lapsed churn_rateregionEast 119 0.076North 88 0.080South 106 0.123West 86 0.163year = sales["order_date"].dt.year# TODO: buyers_2023 and buyers_2024: one-column DataFrames of distinct customer_id# TODO: left merge with indicator=True and validate="one_to_one"; keep left_only# TODO: join region, plan and churned from customers indexed by customer_id# TODO: per region: lapsed (count) and churn_rate (mean of churned)Hint 1
pd.DataFrame({"customer_id": sales.loc[year == 2023, "customer_id"].unique()}) gives one row per 2023 buyer.
Hint 2
join matches on the index. Set customer_id as the index on both sides: lapsed.set_index("customer_id").join(customers.set_index("customer_id")[cols]).
Solution
year = sales["order_date"].dt.yearids = sales["customer_id"]buyers_2023 = pd.DataFrame({"customer_id": ids[year == 2023].unique()})buyers_2024 = pd.DataFrame({"customer_id": ids[year == 2024].unique()})status = buyers_2023.merge( buyers_2024, on="customer_id", how="left", indicator=True, validate="one_to_one")print(status["_merge"].value_counts().to_dict())lapsed = status.query("_merge == 'left_only'").set_index("customer_id")customer_info = customers.set_index("customer_id")[["region", "plan", "churned"]]info = lapsed[[]].join(customer_info)by_region = info.groupby("region").agg( lapsed=("plan", "size"), churn_rate=("churned", "mean"))print(by_region.round(3))assert len(info) == len(lapsed)assert info["region"].notna().all()assert not lapsed.index.isin(buyers_2024["customer_id"]).any(){'both': 1524, 'left_only': 399, 'right_only': 0} lapsed churn_rateregionEast 119 0.076North 88 0.080South 106 0.123West 86 0.163How it works:
- Each buyer table has one row per customer, so the merge is one-to-one, and
validatechecks it. - The left merge keeps every 2023 buyer.
_mergeisbothfor customers who also bought in 2024 andleft_onlyfor the 399 who did not. Selectingleft_onlyis the anti-join. lapsed[[]]keeps the index and no columns.joinadds the customer columns by matching index labels. Its default ishow="left", so every lapsed buyer stays, which the first assert checks.- Lapsed buyers churn less often than the 19.3% of all customers. Not ordering in the shop and cancelling the subscription are different behaviors, so a “lapsed” flag is not a churn label.
Alternative: buyers_2023[~buyers_2023["customer_id"].isin(buyers_2024["customer_id"])] gives the same 399 customers with a mask. The merge version also shows how many buyers stayed.
Challenge
Section titled “Challenge”M25-X01 · Signup cohorts: who keeps buying?
Section titled “M25-X01 · Signup cohorts: who keeps buying?”A cohort is a group of customers who share a start date. Take the customers who signed up from January to June 2023. For each signup month (the cohort) and each month since signup (0 to 5), compute the share of the cohort’s customers who placed at least one order in that month. Divide by the full cohort size from customers, so that customers who never ordered count too.
[69, 86, 98, 91, 99, 89]months_since 0 1 2 3 4 5cohort2023-01 0.130 0.145 0.188 0.174 0.232 0.1742023-02 0.081 0.198 0.105 0.140 0.186 0.1282023-03 0.102 0.153 0.184 0.194 0.204 0.1222023-04 0.165 0.242 0.209 0.286 0.132 0.1432023-05 0.182 0.101 0.192 0.182 0.182 0.1922023-06 0.112 0.202 0.213 0.258 0.202 0.315# TODO: cohort customers: signup_date from 2023-01-01 to 2023-06-30, cohort = signup month# TODO: merge their sales lines (validate many_to_one); months_since = order month - signup month# TODO: pivot_table: index cohort, columns months_since (0-5), values customer_id, aggfunc nunique# TODO: divide each row by the cohort size and print, rounded to 3 decimalsHint 1
A month number year * 12 + month turns “months since” into a subtraction of two integers.
Hint 2
Cohort sizes come from the customers table: cohort_customers.groupby("cohort").size(). Divide the pivot table by it with .div(sizes, axis=0).
Hint 3
Filter months_since to 0–5 before the pivot, and pass fill_value=0 for cohort months with no buyers.
Solution
signup = pd.to_datetime(customers["signup_date"])cohort_customers = customers.assign( signup=signup, cohort=signup.dt.to_period("M")).query("'2023-01-01' <= signup <= '2023-06-30'")[["customer_id", "signup", "cohort"]]
orders = sales[["customer_id", "order_date"]].merge( cohort_customers, on="customer_id", how="inner", validate="many_to_one")month_number = orders["order_date"].dt.year * 12 + orders["order_date"].dt.monthsignup_number = orders["signup"].dt.year * 12 + orders["signup"].dt.monthorders = orders.assign(months_since=month_number - signup_number)
active = orders.query("0 <= months_since <= 5").pivot_table( index="cohort", columns="months_since", values="customer_id", aggfunc="nunique", fill_value=0,)sizes = cohort_customers.groupby("cohort").size()retention = active.div(sizes, axis=0)print(sizes.to_list())print(retention.round(3))assert (orders["months_since"] >= 0).all()assert retention.shape == (6, 6)assert ((retention >= 0) & (retention <= 1)).all().all()[69, 86, 98, 91, 99, 89]months_since 0 1 2 3 4 5cohort2023-01 0.130 0.145 0.188 0.174 0.232 0.1742023-02 0.081 0.198 0.105 0.140 0.186 0.1282023-03 0.102 0.153 0.184 0.194 0.204 0.1222023-04 0.165 0.242 0.209 0.286 0.132 0.1432023-05 0.182 0.101 0.192 0.182 0.182 0.1922023-06 0.112 0.202 0.213 0.258 0.202 0.315How it works:
querywith a date string filters the 2023 H1 signups.to_period("M")labels each customer’s cohort.- The inner merge keeps only the sales lines of cohort customers and adds their signup date. It is many-to-one, so
validateguards it. - The month numbers make “months since signup” an integer. The first assert checks that no order comes before its signup, as the data dictionary promises.
nuniquecounts customers, not lines, in each cell. Dividing by the full cohort size, not by the month-0 column, keeps customers who never ordered in the denominator.- In any month, only 8% to 32% of a cohort buys. In no cohort is the signup month the most active one: customers keep buying, and often more, in the months after. A retention table is for such comparisons: read along a row to see how a cohort develops, and down a column to see whether newer cohorts behave like older ones.
Alternative: (orders["order_date"].dt.to_period("M") - orders["cohort"]).apply(lambda off: off.n) computes the month difference from periods, but it runs a Python function per row. The integer month numbers are vectorized.
M25-X02 · A store scorecard with ranks within each region
Section titled “M25-X02 · A store scorecard with ranks within each region”Build a 2024 scorecard with one row per store: city, region, revenue (2024, in thousands), per_sqm (2024 revenue per square meter), growth (2024 vs 2023) and rank (1 = highest growth within the store’s region). Sort by region and rank. Then print the best store of each region.
store_id city region revenue per_sqm growth rank S07 New York East 263.924 77.625 0.291 1 S09 Philadelphia East 132.488 75.277 0.181 2 S08 Boston East 148.353 72.367 0.121 3 S01 Chicago North 220.899 77.508 0.190 1 S03 Detroit North 115.187 81.117 0.176 2 S02 Minneapolis North 141.644 72.638 0.116 3 S06 Miami South 111.360 66.286 0.316 1 S05 Atlanta South 160.171 69.640 0.143 2 S04 Houston South 210.733 67.978 0.140 3 S12 Denver West 91.760 67.970 0.506 1 S10 Seattle West 213.238 85.983 0.133 2 S11 San Francisco West 141.176 74.696 0.106 3region store_id city growth East S07 New York 0.291 North S01 Chicago 0.190 South S06 Miami 0.316 West S12 Denver 0.506# TODO: yearly revenue per store, unstack the years# TODO: merge with stores (validate one_to_one) for city, region, size_sqm# TODO: per_sqm, growth, rank within region with groupby(...).rank(...)# TODO: sort, print, and print the rank-1 store per regionHint 1
sales.groupby(["store_id", year])["revenue"].sum().unstack() gives one row per store and one column per year.
Hint 2
card.groupby("region")["growth"].rank(ascending=False) ranks within each region and returns one value per row, like transform.
Hint 3
After unstack, the year columns are integers (2023 and 2024). Rename them before the merge, for example to rev_2023 and rev_2024.
Solution
year = sales["order_date"].dt.year.rename("year")by_year = ( sales.groupby(["store_id", year])["revenue"].sum() .unstack("year") .rename(columns={2023: "rev_2023", 2024: "rev_2024"}) .reset_index())card = by_year.merge( stores[["store_id", "city", "region", "size_sqm"]], on="store_id", validate="one_to_one",)card = card.assign( revenue=card["rev_2024"] / 1000, per_sqm=card["rev_2024"] / card["size_sqm"], growth=card["rev_2024"] / card["rev_2023"] - 1,)card["rank"] = card.groupby("region")["growth"].rank(ascending=False).astype(int)card = card.sort_values(["region", "rank"])[ ["store_id", "city", "region", "revenue", "per_sqm", "growth", "rank"]]print(card.round(3).to_string(index=False))best = card.query("rank == 1")[["region", "store_id", "city", "growth"]]print(best.round(3).to_string(index=False))assert len(card) == 12assert card.groupby("region")["rank"].agg(lambda r: sorted(r) == [1, 2, 3]).all()store_id city region revenue per_sqm growth rank S07 New York East 263.924 77.625 0.291 1 S09 Philadelphia East 132.488 75.277 0.181 2 S08 Boston East 148.353 72.367 0.121 3 S01 Chicago North 220.899 77.508 0.190 1 S03 Detroit North 115.187 81.117 0.176 2 S02 Minneapolis North 141.644 72.638 0.116 3 S06 Miami South 111.360 66.286 0.316 1 S05 Atlanta South 160.171 69.640 0.143 2 S04 Houston South 210.733 67.978 0.140 3 S12 Denver West 91.760 67.970 0.506 1 S10 Seattle West 213.238 85.983 0.133 2 S11 San Francisco West 141.176 74.696 0.106 3region store_id city growth East S07 New York 0.291 North S01 Chicago 0.190 South S06 Miami 0.316 West S12 Denver 0.506How it works:
- The groupby and
unstackgive one row per store with the two yearly totals. The rename gives the year columns string names, which are safer in later code. - The merge is one-to-one (one row per store on both sides).
validatechecks it. assigncomputes the three ratio columns from the totals.groupby("region")["growth"].rank(ascending=False)ranks each store within its region, so the result lines up with the rows. The last assert checks that every region has the ranks 1, 2 and 3.to_string(index=False)hides the row labels, which mean nothing after the sort. S12’s growth tops the West, but it opened in mid-2023; a report should say so.
Alternative: card.loc[card.groupby("region")["growth"].idxmax()] finds the best store of each region without a rank column.
M25-X03 · Did the campaigns lift web traffic?
Section titled “M25-X03 · Did the campaigns lift web traffic?”A campaign day has marketing_spend above 2,000 USD. Consecutive campaign days form one campaign. For each campaign, report the start date, the number of days, the mean visits during the campaign, the mean visits of the 14 days before it (the baseline) and the uplift (campaign mean / baseline − 1).
start days visits baseline upliftcampaign1 2022-03-14 5 6778.600 3164.143 1.1422 2022-09-06 4 7103.500 3474.385 1.0453 2023-02-20 6 7637.500 3759.500 1.0324 2023-06-12 3 10033.667 3576.857 1.8055 2023-10-02 5 7792.600 3871.357 1.0136 2024-04-08 4 13575.250 4917.500 1.7617 2024-09-16 7 9467.286 5162.214 0.834mean uplift: 1.233is_campaign = web["marketing_spend"] > 2000# TODO: campaign_id: a new id every time a campaign starts (compare with shift, then cumsum)# TODO: baseline = mean visits of the previous 14 days (rolling + shift)# TODO: per campaign: start, days, visits, baseline at the start day, upliftHint 1
A campaign starts on a day where is_campaign is True and the previous day’s value is False: is_campaign & ~is_campaign.shift(1, fill_value=False).
Hint 2
start.cumsum() numbers the campaigns. Keep only the campaign days before you group.
Hint 3
web["visits"].rolling(14, min_periods=10).mean().shift(1) is the baseline for each day. Take its value on the first day of each campaign with "first".
Solution
is_campaign = web["marketing_spend"] > 2000start = is_campaign & ~is_campaign.shift(1, fill_value=False)campaign_id = start.cumsum()baseline = web["visits"].rolling(14, min_periods=10).mean().shift(1)
days = web.assign(campaign=campaign_id, baseline=baseline)[is_campaign]report = days.groupby("campaign").agg( start=("visits", lambda s: s.index.min().date()), days=("visits", "size"), visits=("visits", "mean"), baseline=("baseline", "first"),)report["uplift"] = report["visits"] / report["baseline"] - 1print(report.round(3))print("mean uplift:", round(report["uplift"].mean(), 3))assert len(report) == 7assert report["days"].sum() == is_campaign.sum()assert (report["uplift"] > 0.5).all() start days visits baseline upliftcampaign1 2022-03-14 5 6778.600 3164.143 1.1422 2022-09-06 4 7103.500 3474.385 1.0453 2023-02-20 6 7637.500 3759.500 1.0324 2023-06-12 3 10033.667 3576.857 1.8055 2023-10-02 5 7792.600 3871.357 1.0136 2024-04-08 4 13575.250 4917.500 1.7617 2024-09-16 7 9467.286 5162.214 0.834mean uplift: 1.233How it works:
shift(1, fill_value=False)gives the previous day’s flag. A day that is a campaign day after a non-campaign day starts a campaign.start.cumsum()adds 1 at each start, so all days of a campaign share an id. Selecting[is_campaign]drops the days between campaigns.- The baseline is a trailing 14-day mean that ends the day before, thanks to
shift(1).min_periods=10tolerates the missing visit days."first"takes the baseline of the campaign’s first day, before the campaign starts lifting the average. - The lambda takes the start date from the group’s index. Every campaign lifts visits by at least 83%, and the mean uplift is 123%. This mean is the average per campaign, not per day.
Alternative: use the median of the previous 28 days as a baseline (rolling(28).median().shift(1)), which is less sensitive to an earlier spike that falls into the window.
M25-X04 · Which categories are bought together?
Section titled “M25-X04 · Which categories are bought together?”Market basket analysis looks for products bought in the same order. Find all pairs of lines in the same order with a self-merge on order_id. Count the pairs per (category, category) combination, and print the five most common combinations and the number of multi-line orders.
6589 4113category_a category_bElectronics Clothing 545Clothing Sports 470Electronics Sports 445Clothing Beauty 436Home Clothing 428Name: pairs, dtype: int64lines = sales[["order_id", "product_id", "category"]]# TODO: pairs = lines.merge(lines, on="order_id", suffixes=("_a", "_b"), validate=...)# TODO: keep each pair once: product_id_a < product_id_b# TODO: count per (category_a, category_b) and print the top fiveHint 1
A merge of a table with itself on order_id pairs every line of an order with every line of the same order, including itself. The relationship is many-to-many.
Hint 2
product_id_a < product_id_b removes the self-pairs and keeps one of (A, B) and (B, A). The product ids are grouped by category (P001–P005 are Electronics), so each combination has one fixed order of the two categories.
Hint 3
pairs.groupby(["category_a", "category_b"]).size().nlargest(5) counts and ranks the combinations.
Solution
lines = sales[["order_id", "product_id", "category"]]pairs = lines.merge( lines, on="order_id", suffixes=("_a", "_b"), validate="many_to_many")pairs = pairs[pairs["product_id_a"] < pairs["product_id_b"]]combos = pairs.groupby(["category_a", "category_b"]).size().rename("pairs")lines_per_order = lines.groupby("order_id").size()multi_orders = (lines_per_order > 1).sum()print(len(pairs), multi_orders)print(combos.nlargest(5))expected_pairs = (lines_per_order * (lines_per_order - 1) // 2).sum()assert len(pairs) == expected_pairsassert pairs["order_id"].nunique() == multi_orders6589 4113category_a category_bElectronics Clothing 545Clothing Sports 470Electronics Sports 445Clothing Beauty 436Home Clothing 428Name: pairs, dtype: int64How it works:
- The self-merge pairs each line with every line of the same order. An order with 3 lines gives 9 rows;
validate="many_to_many"documents that this is intended. product_id_a < product_id_bkeeps each unordered pair once and drops the self-pairs. An order with k lines keeps k × (k − 1) / 2 pairs, which the first assert checks.- The groupby counts the pairs per category combination. The most common pairs mix the largest categories. Pairs inside one category also occur but are not in the top five (Clothing with Clothing has 210).
- Counts favor big categories. A next step divides by what you would expect by chance, a measure called lift.
Alternative: pd.crosstab(pairs["category_a"], pairs["category_b"]) shows all combinations as a 6 × 6 table, which is easier to scan than a list.
M25-X05 · A reusable memory optimizer
Section titled “M25-X05 · A reusable memory optimizer”Write a function optimize(df, max_ratio=0.05) that returns a smaller copy of a DataFrame. It converts each str column whose number of distinct values is below max_ratio × the number of rows to category, and downcasts each int64 column with pd.to_numeric. It leaves floats and dates alone. Apply it to sales and customers. Print the memory before and after, the converted columns and check that a groupby result does not change. In a comment, justify the default of 0.05.
sales 3.25 -> 1.38 MB category: store_id, region, channel, product_id, product, category int8: quantitycustomers 0.85 -> 0.33 MB category: region, plan, contract, payment_method int8: age, has_autopay, tenure_months, support_tickets, logins_last_30d, churneddef optimize(df: pd.DataFrame, max_ratio: float = 0.05) -> pd.DataFrame: # TODO: for each str column with few distinct values -> category # TODO: for each int64 column -> pd.to_numeric(..., downcast="integer") ...
# TODO: apply to sales and customers; print MB before and after and the changed dtypes# TODO: check that a groupby result is unchangedHint 1
Loop over df.columns and test df[col].dtype == "str" and df[col].dtype == "int64". Collect the conversions in a dict and apply them with assign(**changes).
Hint 2
df[col].nunique() / len(df) is the share of distinct values. A low share means low cardinality.
Hint 3
int(df.memory_usage(deep=True).sum()) gives the total bytes. Divide by 1e6 for MB.
Solution
def optimize(df: pd.DataFrame, max_ratio: float = 0.05) -> pd.DataFrame: """Return a copy with categories for low-cardinality text and small integers.
max_ratio=0.05: a column qualifies when each distinct value repeats at least 20 times on average. Then the codes (1-2 bytes per row) plus one copy of each text are much smaller than the text per row. Ids, with mostly distinct values, stay str. """ changes = {} for col in df.columns: s = df[col] if s.dtype == "str" and s.nunique() < max_ratio * len(s): changes[col] = s.astype("category") elif s.dtype == "int64": changes[col] = pd.to_numeric(s, downcast="integer") return df.assign(**changes)
def megabytes(df: pd.DataFrame) -> float: return round(int(df.memory_usage(deep=True).sum()) / 1e6, 2)
for name, table in [("sales", sales), ("customers", customers)]: small = optimize(table) changed = { col: str(small[col].dtype) for col in table.columns if small[col].dtype != table[col].dtype } print(name, megabytes(table), "->", megabytes(small), "MB") for dtype in sorted(set(changed.values())): print(f" {dtype}:", ", ".join(c for c, d in changed.items() if d == dtype)) assert megabytes(small) < 0.5 * megabytes(table)
small_sales = optimize(sales)before = sales.groupby("region")["revenue"].sum()after = small_sales.groupby("region")["revenue"].sum()assert before.round(2).to_list() == after.round(2).to_list()assert small_sales["order_id"].dtype == "str"sales 3.25 -> 1.38 MB category: store_id, region, channel, product_id, product, category int8: quantitycustomers 0.85 -> 0.33 MB category: region, plan, contract, payment_method int8: age, has_autopay, tenure_months, support_tickets, logins_last_30d, churnedHow it works:
- The function builds a dict of converted columns and applies it with
assign(**changes), so the input DataFrame never changes. - A
strcolumn becomescategoryonly when it has few distinct values. Insales,order_id(14,877 distinct values) andcustomer_idstaystr; incustomers,customer_idandsignup_date(still text) staystr. pd.to_numeric(downcast="integer")picks the smallest integer dtype that holds every value: hereint8for every integer column, because all values fit in −128 to 127.- Both tables shrink to less than half their size, and the regional totals stay the same. Floats are untouched, so money keeps full precision.
Alternative: decide per column by hand and pass the dtypes to read_csv(dtype=...), as in lesson Example 8. That is the best choice for a fixed file you load every day; the function is for exploring new files.