Skip to content

24. pandas fundamentals — Exercises

These exercises practice every idea of the pandas fundamentals lesson. They use the course datasets: sales lines, customers, houses, products, sensor readings and the nested customer JSON.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block below into the top of a script (for example exercise.py). Then copy the starter code under it and replace each to-do comment with your code.
  3. Run the script with python exercise.py from your project folder, the folder that holds data/. Compare your output with the expected output.
  4. 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 prove that the numbers are right, not only that they look right.

Every exercise starts with this block. It imports pandas and NumPy, fixes the display, creates the output/ folder and loads three datasets.

from pathlib import Path
import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
Path("output").mkdir(exist_ok=True)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
customers = pd.read_csv("data/customers.csv")
houses = pd.read_csv("data/houses.csv", parse_dates=["sold_date"])
Warm-up

The warehouse reports stock for four products: P001 has 120 units, P006 has 0, P019 has 0 and P021 has 45. Build a Series named stock with the product ids as the index. Print it, then print the stock of P021 and the number of products that are out of stock.

Expected output
P001 120
P006 0
P019 0
P021 45
Name: stock, dtype: int64
P021: 45
out of stock: 2
Starter
# TODO: build the Series with index=[...] and name="stock"
# TODO: print the Series
# TODO: print the value for P021 and the count of zeros
Hint 1

pd.Series(values, index=labels, name="stock") builds a labeled Series.

Hint 2

stock["P021"] looks a value up by label. (stock == 0).sum() counts the zeros, because True counts as 1.

Solution
stock = pd.Series([120, 0, 0, 45], index=["P001", "P006", "P019", "P021"], name="stock")
print(stock)
print("P021:", stock["P021"])
print("out of stock:", (stock == 0).sum())
assert stock.dtype == "int64"
assert stock["P021"] == 45
assert (stock == 0).sum() == 2
Output
P001 120
P006 0
P019 0
P021 45
Name: stock, dtype: int64
P021: 45
out of stock: 2

How it works:

  1. The list gives the values and index= gives one label per value, in the same order.
  2. name="stock" appears in the last line of the print. It becomes the column name if you add the Series to a DataFrame.
  3. stock == 0 is a boolean Series. Its sum counts the True values.

Alternative: build the Series from a dict. The keys become the index.

stock = pd.Series({"P001": 120, "P006": 0, "P019": 0, "P021": 45}, name="stock")
print(stock.index.to_list())
Output
['P001', 'P006', 'P019', 'P021']
Warm-up

Build a DataFrame stores from a dict with the columns store_id (S10, S11, S12), city (Seattle, San Francisco, Denver) and size_sqm (2480, 1890, 1350). Print the frame, its shape, its column names as a list and its dtypes.

Expected output
store_id city size_sqm
0 S10 Seattle 2480
1 S11 San Francisco 1890
2 S12 Denver 1350
(3, 3)
['store_id', 'city', 'size_sqm']
store_id str
city str
size_sqm int64
dtype: object
Starter
# TODO: build the DataFrame from a dict of lists
# TODO: print the frame, .shape, the columns as a list and .dtypes
Hint 1

Each dict key is a column name. Each value is the list of that column’s values.

Hint 2

stores.columns.to_list() turns the column Index into a plain list.

Solution
stores = pd.DataFrame(
{
"store_id": ["S10", "S11", "S12"],
"city": ["Seattle", "San Francisco", "Denver"],
"size_sqm": [2480, 1890, 1350],
}
)
print(stores)
print(stores.shape)
print(stores.columns.to_list())
print(stores.dtypes)
assert stores.shape == (3, 3)
assert stores["size_sqm"].sum() == 5720
assert stores["city"].dtype == "str"
Output
store_id city size_sqm
0 S10 Seattle 2480
1 S11 San Francisco 1890
2 S12 Denver 1350
(3, 3)
['store_id', 'city', 'size_sqm']
store_id str
city str
size_sqm int64
dtype: object

How it works:

  1. pandas builds one column per key and a RangeIndex 0, 1, 2 for the rows.
  2. .shape is (rows, columns).
  3. The text columns get the pandas 3 str dtype; the sizes get int64.

Alternative: build the frame from a list of row dicts, the shape that JSON APIs return. pd.DataFrame([{"store_id": "S10", "city": "Seattle", "size_sqm": 2480}, ...]) gives the same frame.

M24-W03 · Predict the output: loc vs iloc

Section titled “M24-W03 · Predict the output: loc vs iloc”
Warm-up

Predict the output: the frame below uses store ids as its index, not in sorted order. Write down what each print shows. Then run the code.

Acceptance criteria:

  • Write your prediction for all four prints before you run the code.
  • Run the code. Your prediction matches the Output in the solution.
  • For each wrong line, name the rule: does the selection use labels or positions, and is the slice end included?
Starter
sizes = pd.DataFrame(
{"size_sqm": [3400, 2850, 1350, 2480]},
index=["S07", "S01", "S12", "S10"],
)
print(sizes.loc["S01":"S12"])
print(sizes.iloc[1:2])
print(sizes.iloc[-1, 0])
print(sizes.loc["S07", "size_sqm"])
# TODO: write your prediction for each print before you run it
Hint 1

loc uses labels and includes the end label. A label slice follows the order of the index, not the alphabet.

Hint 2

iloc uses positions 0, 1, 2… and excludes the end position. -1 is the last position.

Solution
sizes = pd.DataFrame(
{"size_sqm": [3400, 2850, 1350, 2480]},
index=["S07", "S01", "S12", "S10"],
)
print(sizes.loc["S01":"S12"])
print(sizes.iloc[1:2])
print(sizes.iloc[-1, 0])
print(sizes.loc["S07", "size_sqm"])
assert len(sizes.loc["S01":"S12"]) == 2
assert sizes.iloc[-1, 0] == 2480
Output
size_sqm
S01 2850
S12 1350
size_sqm
S01 2850
2480
3400

How it works:

  1. loc["S01":"S12"] runs from the label S01 to the label S12 in index order, both included: S01 and S12.
  2. iloc[1:2] is position 1 only, because the end position 2 is excluded. Position 1 is S01.
  3. iloc[-1, 0] is the last row, first column: S10’s 2480.
  4. loc["S07", "size_sqm"] is one cell, so pandas returns a plain number, not a frame.

Alternative: for one cell, sizes.at["S07", "size_sqm"] and sizes.iat[-1, 0] are the faster single-value forms.

Warm-up

data/web_traffic.csv has 6 columns. Load only date, visits and signups, with date as a datetime column. Print the shape, the dtypes and the number of missing values in visits.

Expected output
(1096, 3)
date datetime64[us]
visits float64
signups int64
dtype: object
missing visits: 5
Starter
traffic = pd.read_csv(
"data/web_traffic.csv",
# TODO: usecols and parse_dates
)
# TODO: print the shape, the dtypes and the missing visits
Hint 1

usecols=["date", "visits", "signups"] and parse_dates=["date"].

Hint 2

traffic["visits"].isna().sum() counts the gaps. A whole-number column with gaps loads as float64.

Solution
traffic = pd.read_csv(
"data/web_traffic.csv",
usecols=["date", "visits", "signups"],
parse_dates=["date"],
)
print(traffic.shape)
print(traffic.dtypes)
print("missing visits:", traffic["visits"].isna().sum())
assert traffic.shape == (1096, 3)
assert traffic["date"].dtype == "datetime64[us]"
assert traffic["visits"].isna().sum() == 5
Output
(1096, 3)
date datetime64[us]
visits float64
signups int64
dtype: object
missing visits: 5

How it works:

  1. usecols reads only three columns. On a big file, this saves time and memory.
  2. parse_dates gives date the dtype datetime64[us].
  3. visits is float64, not int64, because 5 tracking-outage days are blank. int64 cannot hold a missing value.

Alternative: pass dtype={"visits": "Int64"} to keep whole numbers with <NA> in the gaps.

traffic = pd.read_csv(
"data/web_traffic.csv", usecols=["date", "visits"], dtype={"visits": "Int64"}
)
print(traffic["visits"].dtype, traffic["visits"].isna().sum())
Output
Int64 5
Warm-up

How are the 5,000 customers split across contract types? Print the counts with value_counts(), then the shares in percent rounded to 1 decimal.

Expected output
contract
month-to-month 2784
one-year 1225
two-year 991
Name: count, dtype: int64
contract
month-to-month 55.7
one-year 24.5
two-year 19.8
Name: proportion, dtype: float64
Starter
# TODO: counts of customers["contract"]
# TODO: shares in percent, rounded to 1 decimal
Hint 1

value_counts(normalize=True) returns shares between 0 and 1.

Hint 2

Multiply the shares by 100, then call .round(1).

Solution
counts = customers["contract"].value_counts()
shares = (customers["contract"].value_counts(normalize=True) * 100).round(1)
print(counts)
print(shares)
assert counts.sum() == 5000
assert counts.index[0] == "month-to-month"
assert shares.sum().round() == 100
Output
contract
month-to-month 2784
one-year 1225
two-year 991
Name: count, dtype: int64
contract
month-to-month 55.7
one-year 24.5
two-year 19.8
Name: proportion, dtype: float64

How it works:

  1. value_counts() counts each distinct value and sorts the result by count, largest first. The result is a Series with the values as its index.
  2. normalize=True divides each count by the total. The Series is then named proportion.
  3. More than half of the customers have a month-to-month contract, the contract type with the highest churn.

Alternative: customers["contract"].value_counts().div(len(customers)).mul(100).round(1) computes the same shares with method chaining.

Warm-up

Fix the bug: this code should count the houses in Lakeview with at least 4 bedrooms, but it raises an error. Fix it and print the count.

Expected output
146 large houses in Lakeview
Starter
big_lakeview = houses[houses["neighborhood"] == "Lakeview" and houses["bedrooms"] >= 4]
print(len(big_lakeview), "large houses in Lakeview")
# TODO: fix the filter
Hint 1

Read the error: The truth value of a Series is ambiguous. Python’s and needs one True or False.

Hint 2

Use & and put each comparison in its own parentheses.

Solution
in_lakeview = houses["neighborhood"] == "Lakeview"
big_lakeview = houses[in_lakeview & (houses["bedrooms"] >= 4)]
print(len(big_lakeview), "large houses in Lakeview")
assert (big_lakeview["neighborhood"] == "Lakeview").all()
assert big_lakeview["bedrooms"].min() >= 4
Output
146 large houses in Lakeview

How it works:

  1. and asks each side for one truth value. A Series of 3,000 values has no single truth value, so pandas raises a ValueError.
  2. & combines the two masks element by element: one result per house.
  3. The parentheses matter. Without them, & runs before == and >=.

Alternative: houses.query("neighborhood == 'Lakeview' and bedrooms >= 4"). Inside a query string, and is allowed.

Warm-up

Print the five most expensive houses with the columns house_id, neighborhood, sqft and price. Use nlargest.

Expected output
house_id neighborhood sqft price
2920 H2921 Lakeview 5710 3730500
2132 H2133 Lakeview 3980 2772500
541 H0542 Maple Grove 3770 2660000
917 H0918 Lakeview 4260 2549000
22 H0023 Oak Hill 5690 2529500
Starter
# TODO: nlargest on price, then select four columns
Hint 1

houses.nlargest(5, "price") returns the five rows with the highest price.

Hint 2

Select the columns afterwards with a list: [["house_id", "neighborhood", "sqft", "price"]].

Solution
top5 = houses.nlargest(5, "price")[["house_id", "neighborhood", "sqft", "price"]]
print(top5)
assert len(top5) == 5
assert top5["price"].is_monotonic_decreasing
assert top5["price"].iloc[0] == houses["price"].max()
Output
house_id neighborhood sqft price
2920 H2921 Lakeview 5710 3730500
2132 H2133 Lakeview 3980 2772500
541 H0542 Maple Grove 3770 2660000
917 H0918 Lakeview 4260 2549000
22 H0023 Oak Hill 5690 2529500

How it works:

  1. nlargest finds the top five without sorting all 3,000 rows.
  2. The double brackets select a list of columns and keep a DataFrame.
  3. The index shows each house’s original row number.
  4. Four of the five are large houses in Lakeview and Oak Hill, and their prices are genuine. H0542 in Maple Grove is different: it is one of the 8 price errors in the file, inflated about 2.5 times. A top-n list is a quick way to spot such values; module 26 tests for outliers properly.

Alternative: houses.sort_values("price", ascending=False).head(5) gives the same rows with a full sort.

M24-W08 · Add a margin column to the products

Section titled “M24-W08 · Add a margin column to the products”
Warm-up

Load data/products.csv. Add a column margin with the share of the price that the shop keeps: (unit_price − unit_cost) / unit_price. Print the three products with the highest margin, with the columns product, unit_price and margin.

Expected output
product unit_price margin
25 Vitamin C Face Serum 24.99 0.748
29 Mineral Sunscreen SPF 50 15.99 0.744
13 Running Socks 3-Pack 14.99 0.720
Starter
products = pd.read_csv("data/products.csv")
# TODO: add the margin column with vectorized arithmetic
# TODO: print the top 3 by margin
Hint 1

products["margin"] = (products["unit_price"] - products["unit_cost"]) / products["unit_price"].

Hint 2

products.nlargest(3, "margin") then select the columns.

Solution
products = pd.read_csv("data/products.csv")
price = products["unit_price"]
products["margin"] = (price - products["unit_cost"]) / price
print(products.nlargest(3, "margin")[["product", "unit_price", "margin"]])
assert products["margin"].between(0, 1).all()
assert products.loc[products["margin"].idxmax(), "product"] == "Vitamin C Face Serum"
Output
product unit_price margin
25 Vitamin C Face Serum 24.99 0.748
29 Mineral Sunscreen SPF 50 15.99 0.744
13 Running Socks 3-Pack 14.99 0.720

How it works:

  1. Each operator works on all 30 rows at once. No loop is needed.
  2. The new column appears at the right end of the frame.
  3. idxmax() in the assert returns the index label of the largest value, which loc uses to find the product name.

Alternative: products.assign(margin=lambda d: 1 - d["unit_cost"] / d["unit_price"]) returns a new frame with the column and leaves products unchanged.

Warm-up

Load the columns store_id, city and opened of data/stores.csv, with opened as a date. Write them to output/stores.jsonl as JSON Lines (one record per line, dates in ISO format). Print the first line of the file. Read the file back, print the dtype of opened, parse it as a date and check that the result equals the frame you saved.

Expected output
{"store_id":"S01","city":"Chicago","opened":"2009-03-14T00:00:00.000"}
str
True
Starter
stores = pd.read_csv(
"data/stores.csv", usecols=["store_id", "city", "opened"], parse_dates=["opened"]
)
# TODO: to_json with orient="records", lines=True and date_format="iso"
# TODO: print the first line of the file
# TODO: read_json(lines=True), print the dtype, parse "opened", compare with equals
Hint 1

stores.to_json(path, orient="records", lines=True, date_format="iso"). Without date_format="iso", pandas 3.1 warns that its default date format will change.

Hint 2

read_json guesses dates only from column names such as date or created_at. opened comes back as text: parse it with pd.to_datetime(back["opened"], format="ISO8601").

Solution
stores = pd.read_csv(
"data/stores.csv", usecols=["store_id", "city", "opened"], parse_dates=["opened"]
)
stores.to_json("output/stores.jsonl", orient="records", lines=True, date_format="iso")
with open("output/stores.jsonl", encoding="utf-8") as f:
print(f.readline(), end="")
back = pd.read_json("output/stores.jsonl", lines=True)
print(back["opened"].dtype)
back["opened"] = pd.to_datetime(back["opened"], format="ISO8601")
print(back.equals(stores))
assert back.equals(stores)
assert len(back) == 12
Output
{"store_id":"S01","city":"Chicago","opened":"2009-03-14T00:00:00.000"}
str
True

How it works:

  1. orient="records" writes one JSON object per row. lines=True puts each object on its own line instead of in one big list.
  2. date_format="iso" writes the dates as ISO 8601 text, such as 2009-03-14T00:00:00.000.
  3. JSON has no date type, and the name opened matches none of the read_json date-name rules, so the column comes back as str.
  4. format="ISO8601" parses any ISO 8601 text, with or without a time part. After that, the frame equals the original, dtypes included.

Alternative: orient="records" without lines=True writes one JSON list, the layout that a web API returns. Use JSON Lines for logs and for large files that another program reads line by line.

Core

Write a short profile of customers: print the shape, the columns that have missing values with their counts, and describe() for age, tenure_months and monthly_charges.

Expected output
(5000, 15)
total_charges 10
dtype: int64
age tenure_months monthly_charges
count 5000.000 5000.000 5000.000
mean 42.263 23.081 60.836
std 12.732 19.754 22.936
min 18.000 0.000 28.050
25% 33.000 7.000 39.960
50% 42.000 17.000 58.865
75% 51.000 34.000 72.005
max 80.000 72.000 143.240
Starter
# TODO: print the shape
# TODO: count missing values per column and keep only the columns above 0
# TODO: describe three numeric columns
Hint 1

customers.isna().sum() gives one count per column, as a Series.

Hint 2

Filter that Series with its own mask: missing[missing > 0].

Solution
print(customers.shape)
missing = customers.isna().sum()
print(missing[missing > 0])
print(customers[["age", "tenure_months", "monthly_charges"]].describe())
assert customers.shape == (5000, 15)
assert missing.sum() == 10
Output
(5000, 15)
total_charges 10
dtype: int64
age tenure_months monthly_charges
count 5000.000 5000.000 5000.000
mean 42.263 23.081 60.836
std 12.732 19.754 22.936
min 18.000 0.000 28.050
25% 33.000 7.000 39.960
50% 42.000 17.000 58.865
75% 51.000 34.000 72.005
max 80.000 72.000 143.240

How it works:

  1. isna() returns a boolean frame; sum() counts the True values per column.
  2. Filtering a Series with a mask on itself keeps only the entries you care about. Only total_charges has gaps: the 10 brand-new customers.
  3. describe() shows that tenure is right-skewed: the mean (23.1) is above the median (17).

Alternative: customers.info() shows the non-null counts of every column in one call. It prints directly, so it is better for a quick look than for a check in code.

M24-C02 · Filter an Excel sheet and save it as Parquet

Section titled “M24-C02 · Filter an Excel sheet and save it as Parquet”
Core

Read the sales sheet of data/sales_sample.xlsx. Keep the online lines, write them to output/online_sample.parquet without the index, read the file back and check that it equals the filtered frame. Print the number of online lines, their total revenue and the dtype of order_date in the file you read back.

Expected output
156 online lines
revenue 30,087.88
datetime64[us]
Starter
sample = pd.read_excel("data/sales_sample.xlsx", sheet_name="sales")
# TODO: keep channel == "online" and reset the index
# TODO: write to output/online_sample.parquet, read it back, compare with equals
Hint 1

After a filter, the index has gaps (0, 3, 7…). reset_index(drop=True) gives it 0, 1, 2… again, so the frame read back from Parquet matches.

Hint 2

online.to_parquet(path, index=False) and pd.read_parquet(path). Then back.equals(online).

Solution
sample = pd.read_excel("data/sales_sample.xlsx", sheet_name="sales")
online = sample[sample["channel"] == "online"].reset_index(drop=True)
online.to_parquet("output/online_sample.parquet", index=False)
back = pd.read_parquet("output/online_sample.parquet")
print(len(online), "online lines")
print(f"revenue {online['revenue'].sum():,.2f}")
print(back["order_date"].dtype)
assert back.equals(online)
assert (back["channel"] == "online").all()
Output
156 online lines
revenue 30,087.88
datetime64[us]

How it works:

  1. The filter keeps the rows where channel is "online". Their labels keep the gaps of the original row numbers.
  2. reset_index(drop=True) numbers the rows again. drop=True throws the old labels away instead of adding them as a column.
  3. With index=False, Parquet does not store the index, and read_parquet builds a fresh RangeIndex. Without the reset, equals would be False because the labels differ.
  4. Parquet stores the date column with its dtype, so it comes back as datetime64[us].

Alternative: keep the filtered index and write it with index=True. Parquet then stores the labels, and read_parquet restores them, so equals is True without the reset.

M24-C03 · Count orders per city from nested JSON

Section titled “M24-C03 · Count orders per city from nested JSON”
Core

From data/customers.json, build one row per order with json_normalize. Each row must carry the customer’s customer_id and the city from the nested address. Print the number of orders and the number of orders per city.

Expected output
48 orders
address.city
Chicago 12
Philadelphia 9
Minneapolis 6
Atlanta 6
San Francisco 5
Miami 5
Denver 3
Seattle 1
New York 1
Name: count, dtype: int64
Starter
import json
with open("data/customers.json", encoding="utf-8") as f:
export = json.load(f)
# TODO: json_normalize with record_path and meta (customer_id, the nested city)
# TODO: print the number of orders and value_counts of the city column
Hint 1

record_path="orders" makes one row per order.

Hint 2

A nested meta field is a list of keys: meta=["customer_id", ["address", "city"]]. Its column is named address.city.

Solution
import json
with open("data/customers.json", encoding="utf-8") as f:
export = json.load(f)
orders = pd.json_normalize(
export["customers"], record_path="orders", meta=["customer_id", ["address", "city"]]
)
print(len(orders), "orders")
print(orders["address.city"].value_counts())
assert len(orders) == 48
assert orders["customer_id"].nunique() == 17
Output
48 orders
address.city
Chicago 12
Philadelphia 9
Minneapolis 6
Atlanta 6
San Francisco 5
Miami 5
Denver 3
Seattle 1
New York 1
Name: count, dtype: int64

How it works:

  1. record_path="orders" walks into each customer’s orders list and makes one row per item.
  2. meta copies parent fields onto each row. The path ["address", "city"] reaches into the nested dict and names the column with a dot.
  3. 17 of the 20 customers have orders; the 3 with an empty list add no rows.

Alternative: flatten the customers first with pd.json_normalize(export["customers"]), then count orders per city with the list lengths: flat["orders"].str.len() gives the number of orders per customer.

Core

The retention team targets customers aged 25 to 35 (inclusive) on a month-to-month contract who pay by electronic check or PayPal. Count them and print their churn rate, and compare it with the churn rate of all customers. Use between and isin.

Expected output
299 customers in the segment
segment churn 37.5%
overall churn 19.3%
Starter
# TODO: three masks: age between 25 and 35, contract, payment method in a list
# TODO: combine them, count the rows and print the two churn rates
Hint 1

between(low, high) includes both ends. isin takes a list of allowed values.

Hint 2

churned is 0 or 1, so its mean is the churn rate. Format it with :.1%.

Solution
age_ok = customers["age"].between(25, 35)
monthly = customers["contract"] == "month-to-month"
pays = customers["payment_method"].isin(["electronic_check", "paypal"])
segment = customers[age_ok & monthly & pays]
print(len(segment), "customers in the segment")
print(f"segment churn {segment['churned'].mean():.1%}")
print(f"overall churn {customers['churned'].mean():.1%}")
assert segment["age"].between(25, 35).all()
assert set(segment["payment_method"]) <= {"electronic_check", "paypal"}
assert segment["churned"].mean() > customers["churned"].mean()
Output
299 customers in the segment
segment churn 37.5%
overall churn 19.3%

How it works:

  1. Each rule is its own named mask, so you can check each one with .sum().
  2. & combines the three masks. Every rule must hold.
  3. The mean of a 0/1 column is the share of 1s. The segment churns at well above the overall rate, so it is a good target.

Alternative: one query string: customers.query("25 <= age <= 35 and contract == 'month-to-month' and payment_method in ['electronic_check', 'paypal']"). A query supports chained comparisons and in with a list.

Core

Refactor: rewrite this filter as a query string that uses the two Python variables with @. Check that both versions select the same rows, and print the shape of the result.

Code to refactor
min_tickets = 4
max_logins = 5
flagged = customers[
(customers["support_tickets"] >= min_tickets)
& (customers["logins_last_30d"] <= max_logins)
& ~(customers["contract"] == "two-year")
]
Expected output
(37, 15)
True
Starter
min_tickets = 4
max_logins = 5
# TODO: the same filter with customers.query("...")
# TODO: compare with the mask version using equals, and print the shape
Hint 1

Inside the string, write @min_tickets to use the Python variable.

Hint 2

~(a == b) is a != b, or not (a == b) inside a query.

Solution
min_tickets = 4
max_logins = 5
by_mask = customers[
(customers["support_tickets"] >= min_tickets)
& (customers["logins_last_30d"] <= max_logins)
& ~(customers["contract"] == "two-year")
]
by_query = customers.query(
"support_tickets >= @min_tickets and logins_last_30d <= @max_logins"
" and contract != 'two-year'"
)
print(by_query.shape)
print(by_query.equals(by_mask))
assert by_query.equals(by_mask)
assert (by_query["contract"] != "two-year").all()
Output
(37, 15)
True

How it works:

  1. @min_tickets reads the Python variable of the same name. Text values need quotes inside the string: 'two-year'.
  2. Two adjacent string literals join into one string, so a long query can span two lines.
  3. equals confirms the same rows, the same labels and the same dtypes.

Alternative: keep the mask but name each part (many_tickets, few_logins, not_two_year). Named masks are better than a query when you reuse the parts or test them separately.

Core

Sort sales by category A to Z, then by revenue from high to low. Keep the first line of each category with drop_duplicates("category"): that is the biggest line of each category. Print the columns category, order_id, product and revenue.

Expected output
category order_id product revenue
16999 Beauty O012498 Electric Toothbrush 719.88
4669 Books O003437 Statistics Made Simple 699.80
5421 Clothing O003982 Slim Fit Jeans 1499.75
2082 Electronics O001531 55-inch 4K Smart TV 5196.00
2706 Home O002003 Espresso Machine 1396.00
1581 Sports O001143 Adjustable Dumbbells 1395.00
Starter
# TODO: sort_values with two keys and two directions
# TODO: drop_duplicates on category keeps the first row of each category
Hint 1

sort_values(["category", "revenue"], ascending=[True, False]).

Hint 2

drop_duplicates("category") keeps the first row it sees for each category, and the sort put the biggest line first.

Solution
ranked = sales.sort_values(
["category", "revenue"], ascending=[True, False], kind="stable"
)
cols = ["category", "order_id", "product", "revenue"]
best = ranked.drop_duplicates("category")[cols]
print(best)
assert best["category"].is_unique
assert len(best) == 6
assert best["revenue"].max() == sales["revenue"].max()
Output
category order_id product revenue
16999 Beauty O012498 Electric Toothbrush 719.88
4669 Books O003437 Statistics Made Simple 699.80
5421 Clothing O003982 Slim Fit Jeans 1499.75
2082 Electronics O001531 55-inch 4K Smart TV 5196.00
2706 Home O002003 Espresso Machine 1396.00
1581 Sports O001143 Adjustable Dumbbells 1395.00

How it works:

  1. The first key sorts the categories alphabetically. Inside each category, the second key puts the highest revenue first.
  2. kind="stable" keeps the file order among lines with equal revenue, so the result is the same on every run.
  3. drop_duplicates("category") keeps the first occurrence of each category value and drops the rest.

Alternative: module 25 does this with groupby("category")["revenue"].idxmax(), which returns the row label of the maximum in each group.

M24-C07 · Fix the bug: price corrections that do not stick

Section titled “M24-C07 · Fix the bug: price corrections that do not stick”
Core

Fix the bug: the data team learned that the price of house H0957 was recorded at 117,500 instead of 335,000. This code tries to correct it, but the price does not change, and pandas prints a ChainedAssignmentError warning. Fix it and print the corrected price.

Expected output
117500 -> 335000
Starter
houses["price"][houses["house_id"] == "H0957"] = 335_000
print(houses.loc[houses["house_id"] == "H0957", "price"].item())
# TODO: fix the assignment
Hint 1

houses["price"] is a separate object under copy-on-write. The assignment changes that object, not houses.

Hint 2

Select the rows and the column in one step: houses.loc[mask, "price"] = 335_000.

Solution
fix = houses["house_id"] == "H0957"
before = houses.loc[fix, "price"].item()
houses.loc[fix, "price"] = 335_000
after = houses.loc[fix, "price"].item()
print(before, "->", after)
assert after == 335_000
assert houses["price"].dtype == "int64"
Output
117500 -> 335000

How it works:

  1. houses["price"][mask] = value is chained assignment: two selections, then an assignment. Under copy-on-write, the first selection behaves as a copy, so houses never changes.
  2. houses.loc[mask, "price"] names the rows and the column in one call, and the assignment reaches houses.
  3. .item() returns the single value of a one-element Series as a plain number.

Alternative: with house_id as the index, the fix is a single-cell assignment: by_id = houses.set_index("house_id"), then by_id.at["H0957", "price"] = 335_000. set_index returns a new frame, so give it a name first.

M24-C08 · Refactor: replace apply with column arithmetic

Section titled “M24-C08 · Refactor: replace apply with column arithmetic”
Core

Refactor: this code estimates each customer’s expected total charges with apply. Rewrite it as one vectorized expression. Check that both give the same values, and print whether the vectorized version is at least 10 times faster.

Code to refactor
def expected_total(row):
return row["monthly_charges"] * row["tenure_months"]
slow = customers.apply(expected_total, axis=1)
Expected output
same values: True
at least 10x faster: True
Starter
import time
# TODO: time the apply version with time.perf_counter()
# TODO: time the vectorized version
# TODO: compare the results and the times
Hint 1

The vectorized version is customers["monthly_charges"] * customers["tenure_months"].

Hint 2

Compare floats with a tolerance: np.allclose(slow, fast).

Solution
import time
def expected_total(row: pd.Series) -> float:
return row["monthly_charges"] * row["tenure_months"]
start = time.perf_counter()
slow = customers.apply(expected_total, axis=1)
apply_time = time.perf_counter() - start
start = time.perf_counter()
fast = customers["monthly_charges"] * customers["tenure_months"]
vector_time = time.perf_counter() - start
print("same values:", np.allclose(slow, fast))
print("at least 10x faster:", apply_time > 10 * vector_time)
assert np.allclose(slow, fast)
Output
same values: True
at least 10x faster: True

How it works:

  1. apply(axis=1) builds a Series for each of the 5,000 rows and calls the Python function 5,000 times.
  2. The vectorized product multiplies the two columns in one compiled loop.
  3. np.allclose compares the two Series element by element with a small tolerance. The page prints a comparison, not a time, because times change between runs.

Alternative: customers.eval("monthly_charges * tenure_months") evaluates the expression from a string, like query. It is also vectorized.

M24-C09 · Translate store ids to cities with map

Section titled “M24-C09 · Translate store ids to cities with map”
Core

sales has a store_id but no city. Load data/stores.csv, use map with a Series to add a city column to sales, and print the number of lines of the four busiest cities. Check that no line is left without a city.

Expected output
city
New York 2541
Chicago 2220
Houston 2199
Seattle 2190
Name: count, dtype: int64
lines without a city: 0
Starter
stores = pd.read_csv("data/stores.csv")
# TODO: a Series of cities indexed by store_id
# TODO: sales["store_id"].map(...) and value_counts().head(4)
Hint 1

stores.set_index("store_id")["city"] is a Series with the store ids as its index.

Hint 2

map with a Series looks each value up in the Series’ index. A value with no match becomes NaN.

Solution
stores = pd.read_csv("data/stores.csv")
city_of = stores.set_index("store_id")["city"]
sales["city"] = sales["store_id"].map(city_of)
print(sales["city"].value_counts().head(4))
print("lines without a city:", sales["city"].isna().sum())
assert sales["city"].notna().all()
assert sales.loc[sales["store_id"] == "S07", "city"].eq("New York").all()
Output
city
New York 2541
Chicago 2220
Houston 2199
Seattle 2190
Name: count, dtype: int64
lines without a city: 0

How it works:

  1. set_index("store_id") makes the store ids the row labels, so the city column becomes a lookup table.
  2. map replaces each store id by the city at that label. It is a vectorized lookup, with no Python call per row.
  3. The busiest cities match the largest stores, because sales volume scales with floor area.

Alternative: a plain dict works too: dict(zip(stores["store_id"], stores["city"])). Module 25 shows the same join with merge, which can add several columns at once.

Core

In data/sales_raw.csv, the discount column loads as str because some cells hold -. Load it twice: once with the defaults, converting with pd.to_numeric(errors="coerce"), and once with na_values=["-"]. Print the dtype and the number of missing discounts for both, and check that the two results are equal.

Expected output
str 17
float64 24
float64 24
same values: True
Starter
plain = pd.read_csv("data/sales_raw.csv")
# TODO: convert plain["discount"] with to_numeric(errors="coerce")
# TODO: read the file again with na_values=["-"] and compare
Hint 1

pd.to_numeric(plain["discount"], errors="coerce") turns - into NaN.

Hint 2

Series.equals treats NaN in the same position as equal.

Solution
plain = pd.read_csv("data/sales_raw.csv")
print(plain["discount"].dtype, plain["discount"].isna().sum())
coerced = pd.to_numeric(plain["discount"], errors="coerce")
print(coerced.dtype, coerced.isna().sum())
clean = pd.read_csv("data/sales_raw.csv", na_values=["-"])["discount"]
print(clean.dtype, clean.isna().sum())
print("same values:", coerced.equals(clean))
assert coerced.equals(clean)
assert clean.isna().sum() == 24
Output
str 17
float64 24
float64 24
same values: True

How it works:

  1. By default, read_csv treats empty cells and N/A as missing (17 here), but not -, so the column stays text.
  2. to_numeric(errors="coerce") converts the numbers and turns each - into NaN: 24 gaps.
  3. na_values=["-"] does the same at load time. Both give 24 gaps. Count before and after a coercion: the 7 new gaps are exactly the 7 dashes.

Alternative: na_values is the better choice when you know the missing-value tokens: the conversion happens once, at read time, and a truly bad value (such as 0,1) still shows up as str instead of silently turning into NaN.

M24-C11 · Choose: which columns should be categorical?

Section titled “M24-C11 · Choose: which columns should be categorical?”
Core

Choose a method and justify it: decide which text columns of customers to convert to category. Use this rule: convert a text column when its number of distinct values is below 5% of the rows. Print each text column with its distinct count and your decision, then print the memory of the text columns before and after.

Expected output
customer_id 5000 keep str
signup_date 1542 keep str
region 4 category
plan 3 category
contract 3 category
payment_method 4 category
493,016 -> 180,230 bytes
Starter
text_cols = customers.select_dtypes(include="str").columns
# TODO: for each column, compare nunique() with 5% of len(customers)
# TODO: convert the chosen columns and compare memory_usage(deep=True)
Hint 1

select_dtypes(include="str") keeps only the text columns.

Hint 2

customers[col].nunique() < 0.05 * len(customers) is the rule. memory_usage(deep=True, index=False).sum() gives the bytes.

Solution
text_cols = customers.select_dtypes(include="str").columns
limit = 0.05 * len(customers)
chosen = []
for col in text_cols:
distinct = customers[col].nunique()
decision = "category" if distinct < limit else "keep str"
if distinct < limit:
chosen.append(col)
print(f"{col:<15} {distinct:>5} {decision}")
before = customers[text_cols].memory_usage(deep=True, index=False).sum()
converted = customers.astype({col: "category" for col in chosen})
after = converted[text_cols].memory_usage(deep=True, index=False).sum()
print(f"{before:,} -> {after:,} bytes")
assert chosen == ["region", "plan", "contract", "payment_method"]
assert after < before / 2
Output
customer_id 5000 keep str
signup_date 1542 keep str
region 4 category
plan 3 category
contract 3 category
payment_method 4 category
493,016 -> 180,230 bytes

How it works:

  1. customer_id is unique per row and signup_date has 1,542 distinct values. As categoricals, they would store almost every value as a category plus a code, so the rule keeps them as str.
  2. The four business columns have 3 or 4 values each. Each row then stores a 1-byte code.
  3. The memory of the text columns drops by more than half. The two str columns now dominate what is left.

Justification: category pays off when values repeat many times and the set of values is fixed. A low ratio of distinct values to rows measures exactly that. The 5% limit is a rule of thumb, not a law: a column with 300 values in 5 million rows also benefits. signup_date should become a datetime, not a category.

M24-C12 · Interpret: what describe says about house prices

Section titled “M24-C12 · Interpret: what describe says about house prices”
Core

Interpret a result: print describe() for the price column of houses, then print the mean divided by the median, rounded to 2 decimals. Answer in two sentences: is the price distribution symmetric, and which statistic better describes a typical house?

Expected output
count 3000
mean 476466
std 318751
min 117500
25% 278500
50% 376000
75% 560375
max 3730500
Name: price, dtype: int64
mean / median: 1.27
Starter
# TODO: describe the price column (round it and show it as int64 to avoid 4.765e+05)
# TODO: print mean / median, rounded to 2 decimals
# TODO: write your interpretation as a comment
Hint 1

The 50% row of describe() is the median.

Hint 2

When the mean is far above the median, a few very large values pull the mean up: the distribution is right-skewed.

Solution
stats = houses["price"].describe()
print(stats.round().astype("int64"))
ratio = stats["mean"] / stats["50%"]
print("mean / median:", round(ratio, 2))
assert stats["mean"] > stats["50%"]
assert stats["max"] > 5 * stats["50%"]
Output
count 3000
mean 476466
std 318751
min 117500
25% 278500
50% 376000
75% 560375
max 3730500
Name: price, dtype: int64
mean / median: 1.27

How it works:

  1. describe() on a Series returns a Series indexed by count, mean, std, min, 25%, 50%, 75% and max. With values this large, pandas prints floats in scientific notation (4.765e+05), so the solution rounds them and shows them as whole numbers.
  2. The mean is about 27% higher than the median, and the maximum is almost 10 times the median.

Interpretation: the distribution is right-skewed: the middle half of the houses cost between about 279,000 and 560,000, but a long tail of expensive houses in Lakeview and Oak Hill pulls the mean up. The median (376,000) describes a typical house better than the mean. The same skew is why models of house prices often predict log(price) (module 35).

M24-C13 · Ordered labels for house condition

Section titled “M24-C13 · Ordered labels for house condition”
Core

The condition column holds 1 to 5. Map it to the labels poor, fair, average, good and excellent, store the result as an ordered categorical in a new column condition_label, and print the counts in category order. Then print how many houses are in good condition or better.

Expected output
condition_label
poor 183
fair 600
average 1413
good 607
excellent 197
Name: count, dtype: int64
good or better: 804
Starter
labels = {1: "poor", 2: "fair", 3: "average", 4: "good", 5: "excellent"}
# TODO: map the numbers to labels
# TODO: astype an ordered CategoricalDtype
# TODO: value_counts(sort=False) and a >= comparison
Hint 1

houses["condition"].map(labels) gives the text labels.

Hint 2

pd.CategoricalDtype(["poor", "fair", "average", "good", "excellent"], ordered=True) defines the order.

Solution
labels = {1: "poor", 2: "fair", 3: "average", 4: "good", 5: "excellent"}
condition_type = pd.CategoricalDtype(list(labels.values()), ordered=True)
houses["condition_label"] = houses["condition"].map(labels).astype(condition_type)
print(houses["condition_label"].value_counts(sort=False))
good_or_better = (houses["condition_label"] >= "good").sum()
print("good or better:", good_or_better)
assert good_or_better == (houses["condition"] >= 4).sum()
assert houses["condition_label"].cat.ordered
Output
condition_label
poor 183
fair 600
average 1413
good 607
excellent 197
Name: count, dtype: int64
good or better: 804

How it works:

  1. map(labels) replaces each number by its label through the dict.
  2. A dict keeps insertion order, so list(labels.values()) lists the labels from poor to excellent.
  3. value_counts(sort=False) keeps category order, which reads naturally from poor to excellent.
  4. >= "good" compares positions in the order, so it matches condition >= 4 exactly.

Alternative: pd.Categorical.from_codes(houses["condition"] - 1, dtype=condition_type) builds the categorical straight from the codes 0 to 4, without the text step.

M24-X01 · A typed loader for the raw export

Section titled “M24-X01 · A typed loader for the raw export”
Challenge

Write a function load_raw_sales(path: str) -> pd.DataFrame that reads data/sales_raw.csv and returns a frame with these dtypes: order_date datetime (parse the three formats %Y-%m-%d, %d/%m/%Y and %B %d, %Y explicitly), unit_price and discount float64, quantity int32, region, channel and category category. Treat "", N/A and - as missing. Print the dtypes of those seven columns and the missing count of each column that has gaps.

Expected output
order_date datetime64[us]
region category
channel category
category category
unit_price float64
quantity int32
discount float64
dtype: object
customer_id 23
region 17
channel 17
unit_price 10
discount 24
dtype: int64
Starter
def load_raw_sales(path: str) -> pd.DataFrame:
df = pd.read_csv(path, na_values=["-"], dtype={...}) # TODO
# TODO: prices: remove "$" and ",", then to_numeric(errors="coerce")
# TODO: dates: three to_datetime calls with errors="coerce", combined with fillna
# TODO: quantity as int32
return df
raw = load_raw_sales("data/sales_raw.csv")
Hint 1

read_csv can set the categoricals: dtype={"region": "category", "channel": "category", "category": "category"}.

Hint 2

Loop over the three formats and fill the gaps of a result Series: parsed = parsed.fillna(pd.to_datetime(text, format=fmt, errors="coerce")).

Hint 3

The region column has messy spellings (north, North). As a categorical, each spelling is its own category for now; module 26 normalizes them.

Solution
DATE_FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]
def load_raw_sales(path: str) -> pd.DataFrame:
"""Read the raw POS export with usable dtypes."""
df = pd.read_csv(
path,
na_values=["-"],
dtype={"region": "category", "channel": "category", "category": "category"},
)
price_text = df["unit_price"].str.replace("$", "").str.replace(",", "")
text_dates = df["order_date"]
parsed = pd.Series(pd.NaT, index=df.index, dtype="datetime64[us]")
for fmt in DATE_FORMATS:
parsed = parsed.fillna(pd.to_datetime(text_dates, format=fmt, errors="coerce"))
return df.assign(
order_date=parsed,
unit_price=pd.to_numeric(price_text, errors="coerce"),
quantity=df["quantity"].astype("int32"),
)
raw = load_raw_sales("data/sales_raw.csv")
cols = ["order_date", "region", "channel", "category"]
cols += ["unit_price", "quantity", "discount"]
print(raw[cols].dtypes)
missing = raw.isna().sum()
print(missing[missing > 0])
assert raw["order_date"].notna().all()
assert raw["order_date"].between("2023-01-01", "2024-12-31").all()
assert raw["unit_price"].isna().sum() == 10
Output
order_date datetime64[us]
region category
channel category
category category
unit_price float64
quantity int32
discount float64
dtype: object
customer_id 23
region 17
channel 17
unit_price 10
discount 24
dtype: int64

How it works:

  1. read_csv already reads "" and N/A as missing; na_values=["-"] adds the dash. discount therefore loads as float64 directly.
  2. The dtype dict creates the three categoricals at read time.
  3. The date loop starts with an all-NaT Series and fills it format by format. Each to_datetime call coerces the values of the other formats to NaT, so they do not overwrite anything.
  4. assign replaces three columns at once and returns the new frame.
  5. The asserts prove that every date parsed and lies inside the sales period, and that only the 10 truly missing prices are NaN.

Alternative: pd.to_datetime(text, format="mixed", dayfirst=True) is one line, but the lesson shows that it reads ISO dates such as 2023-01-04 as 1 April. The explicit loop costs three lines and is correct.

M24-X02 · Customer table with order counts from JSON

Section titled “M24-X02 · Customer table with order counts from JSON”
Challenge

From data/customers.json, build a flat customer table with the columns customer_id, name, plan, city (from the address) and n_orders, the number of orders of each customer (0 for customers with no orders). Count the orders from a second, order-level json_normalize and bring the counts back with map. Sort by n_orders from high to low, then by customer_id, print the first five rows and save the table to output/customer_orders.csv.

Expected output
customer_id name plan city n_orders
0 C00001 Ana Silva premium Chicago 5
2 C00003 Mei Chen premium San Francisco 5
5 C00006 Tom Becker basic Chicago 5
15 C00016 Grace Kim basic Miami 5
18 C00019 Ravi Patel standard Atlanta 5
3 customers without orders
Starter
import json
with open("data/customers.json", encoding="utf-8") as f:
export = json.load(f)
# TODO: flat customers (json_normalize) with a renamed city column
# TODO: order rows (record_path="orders", meta=["customer_id"])
# TODO: counts = orders["customer_id"].value_counts(); map them; fill the gaps with 0
# TODO: sort with two keys, print head(5), save to CSV
Hint 1

rename(columns={"address.city": "city"}) gives the nested column a short name.

Hint 2

value_counts() returns a Series indexed by customer id, which is exactly the lookup table that map needs.

Hint 3

Customers without orders get NaN from map. .fillna(0).astype("int64") turns them into 0.

Solution
import json
with open("data/customers.json", encoding="utf-8") as f:
export = json.load(f)
flat = pd.json_normalize(export["customers"]).rename(columns={"address.city": "city"})
orders = pd.json_normalize(
export["customers"], record_path="orders", meta=["customer_id"]
)
orders_per_customer = orders["customer_id"].value_counts()
table = flat[["customer_id", "name", "plan", "city"]].assign(
n_orders=lambda d: (
d["customer_id"].map(orders_per_customer).fillna(0).astype("int64")
)
)
table = table.sort_values(["n_orders", "customer_id"], ascending=[False, True])
print(table.head(5))
table.to_csv("output/customer_orders.csv", index=False)
print((table["n_orders"] == 0).sum(), "customers without orders")
assert table["n_orders"].sum() == 48
assert len(pd.read_csv("output/customer_orders.csv")) == 20
Output
customer_id name plan city n_orders
0 C00001 Ana Silva premium Chicago 5
2 C00003 Mei Chen premium San Francisco 5
5 C00006 Tom Becker basic Chicago 5
15 C00016 Grace Kim basic Miami 5
18 C00019 Ravi Patel standard Atlanta 5
3 customers without orders

How it works:

  1. The customer-level json_normalize flattens the address. rename shortens the city column.
  2. The order-level json_normalize makes one row per order with its customer_id. value_counts turns that into orders per customer.
  3. map looks each customer up in the counts. The three customers with no orders are missing from the counts, so they get NaN, then 0.
  4. The two-key sort puts the most active customers first and breaks ties by id.

Alternative: skip the second json_normalize and count the list lengths directly: flat["orders"].str.len(). It works because the orders column holds Python lists; .str.len() returns the length of each list.

Challenge

Assign each customer a risk tier. high: month-to-month contract and either tenure of 6 months or less or 3 logins or fewer in 30 days. medium: month-to-month (and not high), or 4 or more support tickets. low: everyone else. Use np.select, the multi-branch version of np.where. Store the tier as an ordered categorical (low < medium < high), print the counts in tier order and the churn rate of each tier.

Expected output
risk
low 2141
medium 1712
high 1147
Name: count, dtype: int64
low churn 6.4%
medium churn 16.2%
high churn 47.8%
Starter
monthly = customers["contract"] == "month-to-month"
# TODO: the other masks
conditions = [...] # TODO: high first, then medium
choices = ["high", "medium"]
# TODO: np.select(conditions, choices, default="low")
# TODO: ordered categorical, counts in order, churn rate per tier
Hint 1

np.select(conditions, choices, default=...) checks the conditions in order and takes the first one that is True for each row.

Hint 2

Because high comes first, the medium condition does not need “and not high”.

Hint 3

For the churn rate of one tier: customers.loc[customers["risk"] == tier, "churned"].mean().

Solution
monthly = customers["contract"] == "month-to-month"
new = customers["tenure_months"] <= 6
inactive = customers["logins_last_30d"] <= 3
many_tickets = customers["support_tickets"] >= 4
conditions = [monthly & (new | inactive), monthly | many_tickets]
risk = np.select(conditions, ["high", "medium"], default="low")
tier_type = pd.CategoricalDtype(["low", "medium", "high"], ordered=True)
customers["risk"] = pd.Series(risk, index=customers.index).astype(tier_type)
print(customers["risk"].value_counts(sort=False))
for tier in tier_type.categories:
rate = customers.loc[customers["risk"] == tier, "churned"].mean()
print(f"{tier:<6} churn {rate:.1%}")
assert customers["risk"].notna().all()
high_contracts = customers.loc[customers["risk"] == "high", "contract"]
assert (high_contracts == "month-to-month").all()
Output
risk
low 2141
medium 1712
high 1147
Name: count, dtype: int64
low churn 6.4%
medium churn 16.2%
high churn 47.8%

How it works:

  1. Each rule is a named mask. new | inactive means either one.
  2. np.select returns a NumPy array of labels. Wrapping it in a Series with the same index keeps it aligned with customers.
  3. The ordered categorical makes value_counts(sort=False) list low, medium and high in that order.
  4. The churn rate rises strongly from tier to tier, so the rules separate customers well. The small loop runs 3 times, once per tier, not once per row; module 25 replaces it with groupby.

Alternative: pd.cut builds ordered tiers from one numeric score. You could compute a score (2 * high_rule + medium_rule) and cut it into bins; module 33 covers binning.

M24-X04 · Refactor: vectorize the sensor status rule

Section titled “M24-X04 · Refactor: vectorize the sensor status rule”
Challenge

Refactor: data/sensors.csv has a status column. The status rule is: fail if vibration ≥ 11.2 or temperature ≥ 42; else warn if vibration ≥ 4.5 or temperature ≥ 33; else ok. The code below applies the rule row by row. Rewrite it with np.select, check that it gives the same result as apply, then compare your result with the status column. Print the counts of your statuses, the number of rows where they differ from the file and how many of those rows have a gap. Explain the difference in a comment.

Code to refactor
def status_of(row):
if row["vibration_mm_s"] >= 11.2 or row["temperature_c"] >= 42:
return "fail"
if row["vibration_mm_s"] >= 4.5 or row["temperature_c"] >= 33:
return "warn"
return "ok"
slow = sensors.apply(status_of, axis=1)
Expected output
same as apply: True
ok 7588
warn 452
fail 24
Name: count, dtype: int64
rows that differ from the file: 1
of them with a gap: 1
Starter
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
vib = sensors["vibration_mm_s"]
temp = sensors["temperature_c"]
# TODO: np.select with the fail rule first
# TODO: compare with apply, then with sensors["status"]
# TODO: inspect the rows that differ: what do they have in common?
Hint 1

conditions = [(vib >= 11.2) | (temp >= 42), (vib >= 4.5) | (temp >= 33)] and choices = ["fail", "warn"].

Hint 2

Look at the missing values of the rows that differ: sensors.loc[differ, ["temperature_c", "vibration_mm_s"]].isna().any(axis=1).

Solution
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
vib = sensors["vibration_mm_s"]
temp = sensors["temperature_c"]
def status_of(row: pd.Series) -> str:
if row["vibration_mm_s"] >= 11.2 or row["temperature_c"] >= 42:
return "fail"
if row["vibration_mm_s"] >= 4.5 or row["temperature_c"] >= 33:
return "warn"
return "ok"
conditions = [(vib >= 11.2) | (temp >= 42), (vib >= 4.5) | (temp >= 33)]
labels = np.select(conditions, ["fail", "warn"], default="ok")
fast = pd.Series(labels, index=sensors.index)
slow = sensors.apply(status_of, axis=1)
print("same as apply:", fast.equals(slow))
print(fast.value_counts())
differ = fast != sensors["status"]
gaps = sensors.loc[differ, ["temperature_c", "vibration_mm_s"]].isna().any(axis=1)
print("rows that differ from the file:", differ.sum())
print("of them with a gap:", gaps.sum())
assert fast.equals(slow)
assert gaps.all()
Output
same as apply: True
ok 7588
warn 452
fail 24
Name: count, dtype: int64
rows that differ from the file: 1
of them with a gap: 1

How it works:

  1. np.select checks the fail rule first, then the warn rule, and uses ok for the rest, exactly like the if chain.
  2. fast.equals(slow) proves the refactor changed nothing. np.select returns a NumPy array of fixed-width strings (dtype <U4); wrapping it in a Series with the sensors’ index converts it to the pandas str dtype and lets equals and != align it.
  3. Only one row differs, and it has a gap in temperature or vibration. A comparison with NaN is False, so a missing reading can never trigger its own rule. Most gaps do not change the status, because the other value already decides it or the reading was normal anyway.

Interpretation: the file computed status before the gaps were injected, so it still knows the true reading. Your rule sees only what is left. In production, decide explicitly what a missing reading means: often unknown, not ok. You could add sensors[["temperature_c", "vibration_mm_s"]].isna().any(axis=1) as a first condition with the choice "unknown".

M24-X05 · Cut the memory of the customer file

Section titled “M24-X05 · Cut the memory of the customer file”
Challenge

Load data/customers.csv twice: once with the defaults and once with a dtype mapping that uses category for the four business text columns, int8 for the small integer columns (age, has_autopay, tenure_months, support_tickets, logins_last_30d, churned) and float32 for the three float columns. Print the memory of both frames in KB with memory_usage(deep=True), the reduction factor, and prove that no value changed: the small frame, converted back to the default dtypes, gives the same numbers (floats within a tolerance of 0.01).

Expected output
default 833 KB, typed 265 KB
3.1x smaller
integers equal: True
floats close: True
text equal: True
Starter
default = pd.read_csv("data/customers.csv")
small_types = {
# TODO: column -> dtype
}
small = pd.read_csv("data/customers.csv", dtype=small_types)
# TODO: memory in KB of both frames, and the factor
# TODO: check the integers exactly and the floats with np.allclose
Hint 1

int8 holds −128 to 127. Check the maximum of each integer column first: default[cols].max().

Hint 2

float32 keeps about 7 significant digits, so total_charges up to 8,322.61 survives to the cent. np.allclose(a, b, atol=0.01, equal_nan=True) compares with a tolerance and treats the 10 gaps as equal.

Solution
default = pd.read_csv("data/customers.csv")
cat_cols = ["region", "plan", "contract", "payment_method"]
int_cols = ["age", "has_autopay", "tenure_months"]
int_cols += ["support_tickets", "logins_last_30d", "churned"]
float_cols = ["monthly_charges", "total_charges", "avg_session_minutes"]
small_types = (
{col: "category" for col in cat_cols}
| {col: "int8" for col in int_cols}
| {col: "float32" for col in float_cols}
)
small = pd.read_csv("data/customers.csv", dtype=small_types)
big_kb = default.memory_usage(deep=True).sum() / 1024
small_kb = small.memory_usage(deep=True).sum() / 1024
print(f"default {big_kb:,.0f} KB, typed {small_kb:,.0f} KB")
print(f"{big_kb / small_kb:.1f}x smaller")
ints_equal = small[int_cols].astype("int64").equals(default[int_cols])
floats_close = all(
np.allclose(small[col], default[col], atol=0.01, equal_nan=True)
for col in float_cols
)
cats_equal = all((small[col].astype("str") == default[col]).all() for col in cat_cols)
print("integers equal:", ints_equal)
print("floats close:", floats_close)
print("text equal:", cats_equal)
assert default[int_cols].max().max() <= 127
assert ints_equal and floats_close and cats_equal
Output
default 833 KB, typed 265 KB
3.1x smaller
integers equal: True
floats close: True
text equal: True

How it works:

  1. The dict union operator | (module 04) merges three dict comprehensions into one dtype mapping.
  2. read_csv applies the dtypes while it parses, so the large default frame never exists in a real low-memory pipeline.
  3. The two str columns (customer_id, signup_date) are now most of the remaining memory. Parsing signup_date as a date would shrink it further.
  4. The checks convert back and compare: integers exactly, floats with a tolerance of one cent, text by value.

Alternative: pd.to_numeric(s, downcast="integer") picks the smallest integer dtype that fits the values for you. It is handy when you do not know the ranges in advance.