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:
- Read the task and the expected output.
- 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. - Run the script with
python exercise.pyfrom your project folder, the folder that holdsdata/. 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 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 npimport 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
Section titled “Warm-up”M24-W01 · Build a Series of stock levels
Section titled “M24-W01 · Build a Series of stock levels”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.
P001 120P006 0P019 0P021 45Name: stock, dtype: int64P021: 45out of stock: 2# TODO: build the Series with index=[...] and name="stock"# TODO: print the Series# TODO: print the value for P021 and the count of zerosHint 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"] == 45assert (stock == 0).sum() == 2P001 120P006 0P019 0P021 45Name: stock, dtype: int64P021: 45out of stock: 2How it works:
- The list gives the values and
index=gives one label per value, in the same order. name="stock"appears in the last line of the print. It becomes the column name if you add the Series to a DataFrame.stock == 0is a boolean Series. Its sum counts theTruevalues.
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())['P001', 'P006', 'P019', 'P021']M24-W02 · Build a DataFrame of stores
Section titled “M24-W02 · Build a DataFrame of stores”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.
store_id city size_sqm0 S10 Seattle 24801 S11 San Francisco 18902 S12 Denver 1350(3, 3)['store_id', 'city', 'size_sqm']store_id strcity strsize_sqm int64dtype: object# TODO: build the DataFrame from a dict of lists# TODO: print the frame, .shape, the columns as a list and .dtypesHint 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() == 5720assert stores["city"].dtype == "str" store_id city size_sqm0 S10 Seattle 24801 S11 San Francisco 18902 S12 Denver 1350(3, 3)['store_id', 'city', 'size_sqm']store_id strcity strsize_sqm int64dtype: objectHow it works:
- pandas builds one column per key and a RangeIndex 0, 1, 2 for the rows.
.shapeis (rows, columns).- The text columns get the pandas 3
strdtype; the sizes getint64.
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”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?
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 itHint 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"]) == 2assert sizes.iloc[-1, 0] == 2480 size_sqmS01 2850S12 1350 size_sqmS01 285024803400How it works:
loc["S01":"S12"]runs from the label S01 to the label S12 in index order, both included: S01 and S12.iloc[1:2]is position 1 only, because the end position 2 is excluded. Position 1 is S01.iloc[-1, 0]is the last row, first column: S10’s 2480.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.
M24-W04 · Load only the columns you need
Section titled “M24-W04 · Load only the columns you need”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.
(1096, 3)date datetime64[us]visits float64signups int64dtype: objectmissing visits: 5traffic = pd.read_csv( "data/web_traffic.csv", # TODO: usecols and parse_dates)# TODO: print the shape, the dtypes and the missing visitsHint 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(1096, 3)date datetime64[us]visits float64signups int64dtype: objectmissing visits: 5How it works:
usecolsreads only three columns. On a big file, this saves time and memory.parse_datesgivesdatethe dtypedatetime64[us].visitsisfloat64, notint64, because 5 tracking-outage days are blank.int64cannot 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())Int64 5M24-W05 · Count contract types
Section titled “M24-W05 · Count contract types”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.
contractmonth-to-month 2784one-year 1225two-year 991Name: count, dtype: int64contractmonth-to-month 55.7one-year 24.5two-year 19.8Name: proportion, dtype: float64# TODO: counts of customers["contract"]# TODO: shares in percent, rounded to 1 decimalHint 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() == 5000assert counts.index[0] == "month-to-month"assert shares.sum().round() == 100contractmonth-to-month 2784one-year 1225two-year 991Name: count, dtype: int64contractmonth-to-month 55.7one-year 24.5two-year 19.8Name: proportion, dtype: float64How it works:
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.normalize=Truedivides each count by the total. The Series is then namedproportion.- 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.
M24-W06 · Fix the bug: and between masks
Section titled “M24-W06 · Fix the bug: and between masks”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.
146 large houses in Lakeviewbig_lakeview = houses[houses["neighborhood"] == "Lakeview" and houses["bedrooms"] >= 4]print(len(big_lakeview), "large houses in Lakeview")# TODO: fix the filterHint 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() >= 4146 large houses in LakeviewHow it works:
andasks each side for one truth value. A Series of 3,000 values has no single truth value, so pandas raises aValueError.&combines the two masks element by element: one result per house.- The parentheses matter. Without them,
&runs before==and>=.
Alternative: houses.query("neighborhood == 'Lakeview' and bedrooms >= 4"). Inside a query string, and is allowed.
M24-W07 · The five most expensive houses
Section titled “M24-W07 · The five most expensive houses”Print the five most expensive houses with the columns house_id, neighborhood, sqft and price. Use nlargest.
house_id neighborhood sqft price2920 H2921 Lakeview 5710 37305002132 H2133 Lakeview 3980 2772500541 H0542 Maple Grove 3770 2660000917 H0918 Lakeview 4260 254900022 H0023 Oak Hill 5690 2529500# TODO: nlargest on price, then select four columnsHint 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) == 5assert top5["price"].is_monotonic_decreasingassert top5["price"].iloc[0] == houses["price"].max() house_id neighborhood sqft price2920 H2921 Lakeview 5710 37305002132 H2133 Lakeview 3980 2772500541 H0542 Maple Grove 3770 2660000917 H0918 Lakeview 4260 254900022 H0023 Oak Hill 5690 2529500How it works:
nlargestfinds the top five without sorting all 3,000 rows.- The double brackets select a list of columns and keep a DataFrame.
- The index shows each house’s original row number.
- 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”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.
product unit_price margin25 Vitamin C Face Serum 24.99 0.74829 Mineral Sunscreen SPF 50 15.99 0.74413 Running Socks 3-Pack 14.99 0.720products = pd.read_csv("data/products.csv")# TODO: add the margin column with vectorized arithmetic# TODO: print the top 3 by marginHint 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"]) / priceprint(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" product unit_price margin25 Vitamin C Face Serum 24.99 0.74829 Mineral Sunscreen SPF 50 15.99 0.74413 Running Socks 3-Pack 14.99 0.720How it works:
- Each operator works on all 30 rows at once. No loop is needed.
- The new column appears at the right end of the frame.
idxmax()in the assert returns the index label of the largest value, whichlocuses 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.
M24-W09 · Save the stores as JSON Lines
Section titled “M24-W09 · Save the stores as JSON Lines”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.
{"store_id":"S01","city":"Chicago","opened":"2009-03-14T00:00:00.000"}strTruestores = 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 equalsHint 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{"store_id":"S01","city":"Chicago","opened":"2009-03-14T00:00:00.000"}strTrueHow it works:
orient="records"writes one JSON object per row.lines=Trueputs each object on its own line instead of in one big list.date_format="iso"writes the dates as ISO 8601 text, such as2009-03-14T00:00:00.000.- JSON has no date type, and the name
openedmatches none of theread_jsondate-name rules, so the column comes back asstr. 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.
M24-C01 · Profile the customer file
Section titled “M24-C01 · Profile the customer file”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.
(5000, 15)total_charges 10dtype: int64 age tenure_months monthly_chargescount 5000.000 5000.000 5000.000mean 42.263 23.081 60.836std 12.732 19.754 22.936min 18.000 0.000 28.05025% 33.000 7.000 39.96050% 42.000 17.000 58.86575% 51.000 34.000 72.005max 80.000 72.000 143.240# TODO: print the shape# TODO: count missing values per column and keep only the columns above 0# TODO: describe three numeric columnsHint 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(5000, 15)total_charges 10dtype: int64 age tenure_months monthly_chargescount 5000.000 5000.000 5000.000mean 42.263 23.081 60.836std 12.732 19.754 22.936min 18.000 0.000 28.05025% 33.000 7.000 39.96050% 42.000 17.000 58.86575% 51.000 34.000 72.005max 80.000 72.000 143.240How it works:
isna()returns a boolean frame;sum()counts theTruevalues per column.- Filtering a Series with a mask on itself keeps only the entries you care about. Only
total_chargeshas gaps: the 10 brand-new customers. 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”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.
156 online linesrevenue 30,087.88datetime64[us]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 equalsHint 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()156 online linesrevenue 30,087.88datetime64[us]How it works:
- The filter keeps the rows where
channelis"online". Their labels keep the gaps of the original row numbers. reset_index(drop=True)numbers the rows again.drop=Truethrows the old labels away instead of adding them as a column.- With
index=False, Parquet does not store the index, andread_parquetbuilds a fresh RangeIndex. Without the reset,equalswould beFalsebecause the labels differ. - 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”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.
48 ordersaddress.cityChicago 12Philadelphia 9Minneapolis 6Atlanta 6San Francisco 5Miami 5Denver 3Seattle 1New York 1Name: count, dtype: int64import 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 columnHint 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) == 48assert orders["customer_id"].nunique() == 1748 ordersaddress.cityChicago 12Philadelphia 9Minneapolis 6Atlanta 6San Francisco 5Miami 5Denver 3Seattle 1New York 1Name: count, dtype: int64How it works:
record_path="orders"walks into each customer’sorderslist and makes one row per item.metacopies parent fields onto each row. The path["address", "city"]reaches into the nested dict and names the column with a dot.- 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.
M24-C04 · Churn in a target segment
Section titled “M24-C04 · Churn in a target segment”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.
299 customers in the segmentsegment churn 37.5%overall churn 19.3%# 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 ratesHint 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()299 customers in the segmentsegment churn 37.5%overall churn 19.3%How it works:
- Each rule is its own named mask, so you can check each one with
.sum(). &combines the three masks. Every rule must hold.- 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.
M24-C05 · Refactor a mask into a query
Section titled “M24-C05 · Refactor a mask into a query”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.
min_tickets = 4max_logins = 5flagged = customers[ (customers["support_tickets"] >= min_tickets) & (customers["logins_last_30d"] <= max_logins) & ~(customers["contract"] == "two-year")](37, 15)Truemin_tickets = 4max_logins = 5# TODO: the same filter with customers.query("...")# TODO: compare with the mask version using equals, and print the shapeHint 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 = 4max_logins = 5by_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()(37, 15)TrueHow it works:
@min_ticketsreads the Python variable of the same name. Text values need quotes inside the string:'two-year'.- Two adjacent string literals join into one string, so a long query can span two lines.
equalsconfirms 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.
M24-C06 · The top line of each category
Section titled “M24-C06 · The top line of each category”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.
category order_id product revenue16999 Beauty O012498 Electric Toothbrush 719.884669 Books O003437 Statistics Made Simple 699.805421 Clothing O003982 Slim Fit Jeans 1499.752082 Electronics O001531 55-inch 4K Smart TV 5196.002706 Home O002003 Espresso Machine 1396.001581 Sports O001143 Adjustable Dumbbells 1395.00# TODO: sort_values with two keys and two directions# TODO: drop_duplicates on category keeps the first row of each categoryHint 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_uniqueassert len(best) == 6assert best["revenue"].max() == sales["revenue"].max() category order_id product revenue16999 Beauty O012498 Electric Toothbrush 719.884669 Books O003437 Statistics Made Simple 699.805421 Clothing O003982 Slim Fit Jeans 1499.752082 Electronics O001531 55-inch 4K Smart TV 5196.002706 Home O002003 Espresso Machine 1396.001581 Sports O001143 Adjustable Dumbbells 1395.00How it works:
- The first key sorts the categories alphabetically. Inside each category, the second key puts the highest revenue first.
kind="stable"keeps the file order among lines with equal revenue, so the result is the same on every run.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”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.
117500 -> 335000houses["price"][houses["house_id"] == "H0957"] = 335_000print(houses.loc[houses["house_id"] == "H0957", "price"].item())# TODO: fix the assignmentHint 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_000after = houses.loc[fix, "price"].item()print(before, "->", after)assert after == 335_000assert houses["price"].dtype == "int64"117500 -> 335000How it works:
houses["price"][mask] = valueis chained assignment: two selections, then an assignment. Under copy-on-write, the first selection behaves as a copy, sohousesnever changes.houses.loc[mask, "price"]names the rows and the column in one call, and the assignment reacheshouses..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”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.
def expected_total(row): return row["monthly_charges"] * row["tenure_months"]
slow = customers.apply(expected_total, axis=1)same values: Trueat least 10x faster: Trueimport time# TODO: time the apply version with time.perf_counter()# TODO: time the vectorized version# TODO: compare the results and the timesHint 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)same values: Trueat least 10x faster: TrueHow it works:
apply(axis=1)builds a Series for each of the 5,000 rows and calls the Python function 5,000 times.- The vectorized product multiplies the two columns in one compiled loop.
np.allclosecompares 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”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.
cityNew York 2541Chicago 2220Houston 2199Seattle 2190Name: count, dtype: int64lines without a city: 0stores = 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()cityNew York 2541Chicago 2220Houston 2199Seattle 2190Name: count, dtype: int64lines without a city: 0How it works:
set_index("store_id")makes the store ids the row labels, so thecitycolumn becomes a lookup table.mapreplaces each store id by the city at that label. It is a vectorized lookup, with no Python call per row.- 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.
M24-C10 · Coerce dirty discounts
Section titled “M24-C10 · Coerce dirty discounts”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.
str 17float64 24float64 24same values: Trueplain = 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 compareHint 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() == 24str 17float64 24float64 24same values: TrueHow it works:
- By default,
read_csvtreats empty cells andN/Aas missing (17 here), but not-, so the column stays text. to_numeric(errors="coerce")converts the numbers and turns each-intoNaN: 24 gaps.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?”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.
customer_id 5000 keep strsignup_date 1542 keep strregion 4 categoryplan 3 categorycontract 3 categorypayment_method 4 category493,016 -> 180,230 bytestext_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").columnslimit = 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 / 2customer_id 5000 keep strsignup_date 1542 keep strregion 4 categoryplan 3 categorycontract 3 categorypayment_method 4 category493,016 -> 180,230 bytesHow it works:
customer_idis unique per row andsignup_datehas 1,542 distinct values. As categoricals, they would store almost every value as a category plus a code, so the rule keeps them asstr.- The four business columns have 3 or 4 values each. Each row then stores a 1-byte code.
- The memory of the text columns drops by more than half. The two
strcolumns 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”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?
count 3000mean 476466std 318751min 11750025% 27850050% 37600075% 560375max 3730500Name: price, dtype: int64mean / median: 1.27# 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 commentHint 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%"]count 3000mean 476466std 318751min 11750025% 27850050% 37600075% 560375max 3730500Name: price, dtype: int64mean / median: 1.27How it works:
describe()on a Series returns a Series indexed bycount,mean,std,min,25%,50%,75%andmax. With values this large, pandas prints floats in scientific notation (4.765e+05), so the solution rounds them and shows them as whole numbers.- 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”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.
condition_labelpoor 183fair 600average 1413good 607excellent 197Name: count, dtype: int64good or better: 804labels = {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 >= comparisonHint 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.orderedcondition_labelpoor 183fair 600average 1413good 607excellent 197Name: count, dtype: int64good or better: 804How it works:
map(labels)replaces each number by its label through the dict.- A dict keeps insertion order, so
list(labels.values())lists the labels from poor to excellent. value_counts(sort=False)keeps category order, which reads naturally from poor to excellent.>= "good"compares positions in the order, so it matchescondition >= 4exactly.
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.
Challenge
Section titled “Challenge”M24-X01 · A typed loader for the raw export
Section titled “M24-X01 · A typed loader for the raw export”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.
order_date datetime64[us]region categorychannel categorycategory categoryunit_price float64quantity int32discount float64dtype: objectcustomer_id 23region 17channel 17unit_price 10discount 24dtype: int64def 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() == 10order_date datetime64[us]region categorychannel categorycategory categoryunit_price float64quantity int32discount float64dtype: objectcustomer_id 23region 17channel 17unit_price 10discount 24dtype: int64How it works:
read_csvalready reads""andN/Aas missing;na_values=["-"]adds the dash.discounttherefore loads asfloat64directly.- The
dtypedict creates the three categoricals at read time. - The date loop starts with an all-
NaTSeries and fills it format by format. Eachto_datetimecall coerces the values of the other formats toNaT, so they do not overwrite anything. assignreplaces three columns at once and returns the new frame.- 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”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.
customer_id name plan city n_orders0 C00001 Ana Silva premium Chicago 52 C00003 Mei Chen premium San Francisco 55 C00006 Tom Becker basic Chicago 515 C00016 Grace Kim basic Miami 518 C00019 Ravi Patel standard Atlanta 53 customers without ordersimport 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 CSVHint 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() == 48assert len(pd.read_csv("output/customer_orders.csv")) == 20 customer_id name plan city n_orders0 C00001 Ana Silva premium Chicago 52 C00003 Mei Chen premium San Francisco 55 C00006 Tom Becker basic Chicago 515 C00016 Grace Kim basic Miami 518 C00019 Ravi Patel standard Atlanta 53 customers without ordersHow it works:
- The customer-level
json_normalizeflattens the address.renameshortens the city column. - The order-level
json_normalizemakes one row per order with itscustomer_id.value_countsturns that into orders per customer. maplooks each customer up in the counts. The three customers with no orders are missing from the counts, so they getNaN, then 0.- 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.
M24-X03 · Risk tiers with np.select
Section titled “M24-X03 · Risk tiers with np.select”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.
risklow 2141medium 1712high 1147Name: count, dtype: int64low churn 6.4%medium churn 16.2%high churn 47.8%monthly = customers["contract"] == "month-to-month"# TODO: the other masksconditions = [...] # TODO: high first, then mediumchoices = ["high", "medium"]# TODO: np.select(conditions, choices, default="low")# TODO: ordered categorical, counts in order, churn rate per tierHint 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"] <= 6inactive = customers["logins_last_30d"] <= 3many_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()risklow 2141medium 1712high 1147Name: count, dtype: int64low churn 6.4%medium churn 16.2%high churn 47.8%How it works:
- Each rule is a named mask.
new | inactivemeans either one. np.selectreturns a NumPy array of labels. Wrapping it in a Series with the same index keeps it aligned withcustomers.- The ordered categorical makes
value_counts(sort=False)list low, medium and high in that order. - 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”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.
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)same as apply: Trueok 7588warn 452fail 24Name: count, dtype: int64rows that differ from the file: 1of them with a gap: 1sensors = 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()same as apply: Trueok 7588warn 452fail 24Name: count, dtype: int64rows that differ from the file: 1of them with a gap: 1How it works:
np.selectchecks the fail rule first, then the warn rule, and usesokfor the rest, exactly like theifchain.fast.equals(slow)proves the refactor changed nothing.np.selectreturns a NumPy array of fixed-width strings (dtype<U4); wrapping it in a Series with the sensors’ index converts it to the pandasstrdtype and letsequalsand!=align it.- Only one row differs, and it has a gap in temperature or vibration. A comparison with
NaNisFalse, 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”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).
default 833 KB, typed 265 KB3.1x smallerintegers equal: Truefloats close: Truetext equal: Truedefault = 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.allcloseHint 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() / 1024small_kb = small.memory_usage(deep=True).sum() / 1024print(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() <= 127assert ints_equal and floats_close and cats_equaldefault 833 KB, typed 265 KB3.1x smallerintegers equal: Truefloats close: Truetext equal: TrueHow it works:
- The dict union operator
|(module 04) merges three dict comprehensions into onedtypemapping. read_csvapplies the dtypes while it parses, so the large default frame never exists in a real low-memory pipeline.- The two
strcolumns (customer_id,signup_date) are now most of the remaining memory. Parsingsignup_dateas a date would shrink it further. - 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.