flowchart TD
subgraph Intake["1. Clean & Audit"]
R1["Raw Survey Copy<br/>strip/title, 999->NaN<br/>to_numeric coerce"]
R2["Group Impute<br/>groupby.transform<br/>per-stratum median"]
end
subgraph Guard["2. Safe Merge"]
M1["pd.merge Left Join<br/>validate=one_to_one"]
M2["Duplicate Key?<br/>Raise MergeError"]
end
subgraph SAC["3. Group & Agg"]
S1["Split by Stratum<br/>or District Panel"]
S2["Apply Named .agg()<br/>or Per-Group shift/roll"]
S3["Combine Tidy Table<br/>Zero Boundary Leakage"]
end
R1 --> R2 --> M1
M1 -. "fail fast" .-> M2
M1 --> S1 --> S2 --> S3
18 Real-World Data Wrangling — Missing Data, Dirty Surveys, Joins, GroupBy, and Time Series
Chapter Mission: Bridge the gap between clean textbook tables and real-world research datasets. Master missing-data diagnostics (MCAR / MAR / MNAR), dirty DHS survey cleaning (sentinels like
999, casing typos like"rural"/"Rural", and safe numeric coercion), guarded relational joins (pd.merge(..., validate="one_to_one")), Split-Apply-Combine named.agg(), and leak-free panel time-series features (shiftandrollingper district)—all written in modern, non-mutating Pandas 3.x Copy-on-Write style.
Chapter Companion Notebooks (1-to-1 Mirrored in Google Colab)
| Lab Type | Interactive Colab Notebook | Scan (Print) |
|---|---|---|
| Walkthrough | ch18 / 01_walkthrough.ipynb | ![]() |
| Guided To-Dos | ch18 / 02_guided_todos.ipynb | ![]() |
| Coding Exam | ch18 / 03_coding_exam.ipynb | ![]() |
Learning Objectives
By the end of this chapter, you will be able to:
- Distinguish MCAR, MAR, and MNAR missingness mechanisms and build deterministic column-level missingness audit tables before and after cleaning.
- Clean dirty household surveys in pure Pandas 3.x style—copying inputs explicitly, normalizing inconsistent string casing (
.str.strip().str.title()), neutralizing DHS sentinel codes (999\(\rightarrow\)NaN), and coercing mixed-type columns safely withpd.to_numeric(..., errors="coerce"). - Impute missing measurements per stratum using
.groupby(...).transform("median")without mutating raw DataFrames or collapsing group differences. - Join relational patient and laboratory tables with
pd.merge(..., how="left", validate="one_to_one")so duplicate keys raiseMergeErrorimmediately instead of silently exploding row counts. - Produce publication-ready Table 1 health-equity summaries using Split-Apply-Combine named
.agg()and engineer zero-leakage panel time-series features (1-week lags and rolling means) strictly within each district.
18.1 Stage 1 — First-Principles Intuition: Why Real Research Data Breaks Clean Code
In Chapter 17, you learned Pandas fundamentals on tidy DataFrames. Real public health surveys (like the Demographic and Health Surveys, DHS) and weekly epidemiological surveillance feeds rarely arrive tidy:
- Hidden Sentinel Codes: Survey interviewers record
"Don't know"as999,99, or-99. If you computemch["anc_visits"].mean()without neutralizing999first, just 8 sentinel rows out of 500 inflate average antenatal care visits from \(3.77\) to an absurd \(19.7\)! - Dirty Categorical Strings: Field enumerators type
"Rural","rural"," rural ", and"URBAN". Left unnormalized,.groupby("residence")splits one stratum into four fragmented rows and corrupts every downstream summary. - Silent Row Explosions in Joins: Joining a 500-patient registry to a lab table that accidentally contains two hemoglobin tests for one patient quietly turns 500 rows into 501+—double-counting that patient in every prevalence estimate.
- Cross-District Time-Series Leakage: Computing
.shift(1)or.rolling(4).mean()on a stacked multi-district table lets Chattogram’s December dengue surge bleed directly into Dhaka’s Week 1 feature!
18.1.1 Missing-Data Mechanisms: MCAR, MAR, and MNAR
Before dropping or imputing a single NaN, ask why the value is missing:
| Mechanism | Meaning | Public Health Example | Safe Wrangling Action |
|---|---|---|---|
| MCAR | Missing Completely At Random | Lab vial dropped on floor | Complete-case or simple imputation is unbiased |
| MAR | Missing At Random (given observed strata) | Rural clinics have more missing Hb tests than urban clinics | Impute within observed strata (e.g., per-residence median) |
| MNAR | Missing Not At Random (depends on unobserved value itself) | Severely ill patients skip follow-up weigh-ins | Do not blindly impute; flag missingness and run sensitivity analysis |
Starting in Pandas 3.x, Copy-on-Write is enforced globally: chained assignments like df["anc_visits"][mask] = np.nan fail or behave unpredictably, and inplace=True is discouraged because it returns None and obscures state mutations. Adopt one clean habit for every wrangling function you write:
- Start with
out = df.copy(). - Transform columns with direct assignment:
out["col"] = .... - End with
return out, leaving the caller’s raw DataFrame untouched.
18.2 Stage 2 — Visual Mental Model: Safe Merge & Split-Apply-Combine Pipeline
Trace the exact order of operations that protects research tables from sentinel distortion, join row explosions, and cross-group leakage:
Notice why stage order is non-negotiable:
- You must normalize
"rural"\(\rightarrow\)"Rural"before grouping to compute per-residence medians, otherwise lowercase rows form their own tiny broken group. - You must replace
999\(\rightarrow\)NaNbefore evaluating thresholds likeanc_visits >= 4, otherwise999 >= 4falsely evaluates toTrue! - You must sort by
["district", "year", "epi_week"]and scope.shift()/.rolling()inside.groupby("district")so every district starts cleanly on Week 1.
18.3 Stage 3 — Line-by-Line Code Walkthrough & Error Anatomy
Open part_04_data_science_math/ch18_data_wrangling_surveys/01_walkthrough.ipynb in Google Colab and run every cell alongside the dissections below using our real bundled mch_survey_sample and epi_surveillance datasets.
18.3.1 Step 0 — Loading Bundled Research Datasets
Expected Output:
18.3.2 Missingness Audit & Cleaning Dirty Surveys
# 1. Audit explicit NaNs BEFORE sentinel cleaning
raw_counts = mch_raw.isna().sum().astype(int)
raw_pct = (raw_counts / len(mch_raw) * 100).round(2)
raw_audit = pd.DataFrame(
{"missing_count": raw_counts, "missing_pct": raw_pct}
).sort_values("missing_pct", ascending=False)
print("Explicit NaNs before cleaning:")
print(raw_audit.head(3))
# 2. Inspect dirty casing and hidden DHS sentinel 999
raw_res = mch_raw["residence"].value_counts().to_dict()
raw_anc_mean = round(mch_raw["anc_visits"].mean(), 2)
print("\nRaw residence counts:", raw_res)
print("Raw anc_visits mean (with 999!):", raw_anc_mean)
# 3. Non-mutating Pandas 3.x cleaning copy
mch = mch_raw.copy()
mch["residence"] = mch["residence"].str.strip().str.title()
mch["anc_visits"] = mch["anc_visits"].replace(999, np.nan)
mch["maternal_hb_g_dl"] = pd.to_numeric(
mch["maternal_hb_g_dl"], errors="coerce"
)
print("Clean residence counts:", mch["residence"].value_counts().to_dict())
print("Clean anc_visits NaNs: ", int(mch["anc_visits"].isna().sum()))
print("Clean anc_visits mean: ", round(mch["anc_visits"].mean(), 2))Expected Output:
Explicit NaNs before cleaning:
missing_count missing_pct
maternal_hb_g_dl 22 4.4
household_id 0 0.0
division 0 0.0
Raw residence counts: {'Rural': 345, 'Urban': 140, 'rural': 11, 'urban': 4}
Raw anc_visits mean (with 999!): 19.7
Clean residence counts: {'Rural': 356, 'Urban': 144}
Clean anc_visits NaNs: 8
Clean anc_visits mean: 3.77Look at that dramatic difference: anc_visits initially showed 0 explicit NaN values, yet hiding inside those 500 rows were 8 sentinel 999 codes that inflated the mean from \(3.77\) to \(19.7\)! Meanwhile, .str.strip().str.title() merged the 11 "rural" and 4 "urban" typos cleanly into Rural (356) and Urban (144).
18.3.3 Group-Median Imputation with .groupby(...).transform("median")
Because hemoglobin missingness differs across strata (16 Rural vs. 6 Urban missing readings, with medians \(11.4\) vs. \(11.6\text{ g/dL}\)), imputing by per-residence median respects MAR structure better than plugging in one global average:
# Check missing Hb by residence (MAR diagnostic) and group medians
hb_na_by_res = mch.groupby("residence")["maternal_hb_g_dl"].apply(
lambda s: int(s.isna().sum())
)
hb_med_by_res = mch.groupby("residence")["maternal_hb_g_dl"].median()
print("Missing Hb by residence:", hb_na_by_res.to_dict())
print("Median Hb by residence: ", hb_med_by_res.to_dict())
# Impute missing Hb with per-residence median (non-mutating copy)
mch_imp = mch.copy()
group_medians = (
mch_imp.groupby("residence")["maternal_hb_g_dl"]
.transform("median")
)
mch_imp["maternal_hb_g_dl"] = mch_imp["maternal_hb_g_dl"].fillna(
group_medians
)
post_means = (
mch_imp.groupby("residence")["maternal_hb_g_dl"]
.mean().round(2).to_dict()
)
print("Remaining Hb NaNs:", int(mch_imp["maternal_hb_g_dl"].isna().sum()))
print("Post-imputation means:", post_means)Expected Output:
Why .transform("median") instead of .median()? .groupby("residence")["maternal_hb_g_dl"].median() collapses the table to 2 rows (Rural, Urban), whereas .transform("median") broadcasts each group’s median back onto all 500 rows with exact index alignment so .fillna(group_medians) fills every missing entry cleanly in one vectorized pass.
18.3.4 Safe Relational Joins with pd.merge(..., validate="one_to_one")
When linking a patient intake table to a separate laboratory table, always specify both how= (usually "left" to retain your full cohort) and validate= to enforce key uniqueness:
patients = pd.DataFrame(
{
"patient_id": ["P-101", "P-102", "P-103", "P-104"],
"residence": ["Rural", "Urban", "Rural", "Urban"],
}
)
labs = pd.DataFrame(
{
"patient_id": ["P-101", "P-102", "P-104", "P-999"],
"ferritin_ng_ml": [18.5, 42.0, 31.2, 25.0],
}
)
joined = pd.merge(
patients, labs, on="patient_id", how="left", validate="one_to_one"
)
print(joined.to_string(index=False))Expected Output:
Notice two critical guarantees here:
- Unmatched patient
P-103stays in the cohort withNaNforferritin_ng_ml(unlikehow="inner", which would silently drop her). - Orphan lab record
P-999is excluded (unlikehow="outer", which would inject an unenrolled person).
18.3.5 Split-Apply-Combine with Named .agg()
Named aggregation (new_col=("source_col", "func")) produces clean, flat-column summary tables in a single readable expression:
wealth_tbl = mch_imp.groupby("wealth_quintile").agg(
n_households=("household_id", "count"),
stunting_pct=("child_stunted", "mean"),
anemia_pct=("maternal_anemia", "mean"),
mean_anc=("anc_visits", "mean"),
)
wealth_tbl["stunting_pct"] = (wealth_tbl["stunting_pct"] * 100).round(1)
wealth_tbl["anemia_pct"] = (wealth_tbl["anemia_pct"] * 100).round(1)
wealth_tbl["mean_anc"] = wealth_tbl["mean_anc"].round(2)
order = ["Poorest", "Poorer", "Middle", "Richer", "Richest"]
print(wealth_tbl.reindex(order))Expected Output:
Because child_stunted and maternal_anemia are binary 0/1 indicators, taking .mean() * 100 directly yields prevalence percentages—revealing a stark socioeconomic gradient from \(28.0\%\) stunting and \(48.6\%\) anemia in the Poorest quintile down to \(8.0\%\) and \(19.5\%\) in the Richest quintile!
18.3.6 Panel Time Series: Per-District Lags & Rolling Windows
Epidemiological surveillance data (epi_surveillance) is a panel dataset: multiple districts tracked repeatedly across weeks and years. Always sort by ["district", "year", "epi_week"] first, then run .shift(1) and .rolling(...) strictly inside .groupby("district"):
epi = epi_raw.sort_values(["district", "year", "epi_week"]).copy()
epi["prev_week_cases"] = epi.groupby("district")["dengue_cases"].shift(1)
epi["rolling_4w"] = (
epi.groupby("district")["dengue_cases"]
.transform(lambda s: s.rolling(window=4, min_periods=1).mean())
.round(2)
)
cols = ["district", "year", "epi_week", "dengue_cases",
"prev_week_cases", "rolling_4w"]
dhaka_top = epi[epi["district"] == "Dhaka"][cols].head(5)
ctg_top = epi[epi["district"] == "Chattogram"][cols].head(3)
print("Dhaka first 5 weeks:")
print(dhaka_top.to_string(index=False))
print("\nChattogram first 3 weeks (zero leakage from Dhaka!):")
print(ctg_top.to_string(index=False))Expected Output:
Dhaka first 5 weeks:
district year epi_week dengue_cases prev_week_cases rolling_4w
Dhaka 2024 1 21 NaN 21.00
Dhaka 2024 2 32 21.0 26.50
Dhaka 2024 3 42 32.0 31.67
Dhaka 2024 4 45 42.0 35.00
Dhaka 2024 5 23 45.0 35.50
Chattogram first 3 weeks (zero leakage from Dhaka!):
district year epi_week dengue_cases prev_week_cases rolling_4w
Chattogram 2024 1 34 NaN 34.00
Chattogram 2024 2 15 34.0 24.50
Chattogram 2024 3 28 15.0 25.67Look closely at Chattogram 2024 Week 1: prev_week_cases is NaN and rolling_4w is 34.00 (its own Week 1 count, thanks to min_periods=1). Zero cases leaked across the district boundary!
18.3.7 Break It On Purpose! (Wrangling Error Anatomy)
Python’s Traceback:
Diagnosis: dup_labs has two rows for "P-101". Without validate="one_to_one", Pandas would silently duplicate "P-101" in the merged table!
Fix: Deduplicate or aggregate dup_labs per patient_id (e.g., taking the latest or mean lab value) before merging.
Python’s Traceback:
Diagnosis: patients uses "patient_id" while misnamed_labs uses "household_id", so on="patient_id" cannot find the join column on the right table.
Fix: Either rename the column first (misnamed_labs.rename(columns={"household_id": "patient_id"})) or pass explicit left_on="patient_id", right_on="household_id".
Python’s Traceback:
Diagnosis: Strict .astype(float) crashes on the very first non-numeric token ("N/A", ".", "", or "missing"), which are ubiquitous in CSV exports from clinic spreadsheets.
Fix: Always cast messy numeric columns with pd.to_numeric(series, errors="coerce") so valid numbers become floats and unparseable tokens cleanly become NaN.
18.4 Stage 4 — The Researcher’s Problem-Structuring Blueprint
Scenario: A Ministry of Health policy brief needs an automated, reproducible function build_equity_brief(raw_mch) that takes a raw DHS maternal-child survey, cleans all dirty casing and sentinel codes, imputes missing maternal hemoglobin by residence median, derives WHO’s 4+ antenatal care visits (anc_4plus) indicator, and outputs a flat, sorted residence \(\times\) wealth_quintile equity table without mutating raw_mch.
18.4.1 Blueprint (Completed on Paper Before Coding)
Non-Mutating Cleaning Sequence (Strict Order):
- Copy
raw_mch(df = raw_mch.copy()). - Normalize
residencewith.str.strip().str.title()first. - Neutralize sentinel
anc_visits == 999\(\rightarrow\)np.nanbefore thresholding. - Coerce
maternal_hb_g_dlviapd.to_numeric(..., errors="coerce")and impute missing values with per-residencemedian via.groupby("residence")["maternal_hb_g_dl"].transform("median"). - Derive
anc_4plus = (df["anc_visits"] >= 4).fillna(False).astype(bool).
- Copy
Stratified Aggregation Contract:
- Group with
groupby(["residence", "wealth_quintile"], as_index=False)so stratification keys stay flat columns. - Compute
n_households,stunting_pct,anemia_pct, andanc4_pct(each percentage scaled by \(100\) and rounded to 1 decimal place). - Sort deterministically by
["residence", "wealth_quintile"]and reset the index.
- Group with
Verification Plan:
- Check
Rural+Poorestvs.Urban+Richest:anc4_pctshould rise sharply with both wealth and urbanicity, andraw_mch["anc_visits"]must still contain its original 8 sentinel999entries untouched.
- Check
18.4.2 Clean Python Implementation (Verbatim in 01_walkthrough.ipynb)
def build_equity_brief(raw_mch):
"""Clean DHS survey and summarize residence x wealth equity gaps."""
df = raw_mch.copy()
df["residence"] = df["residence"].str.strip().str.title()
df["anc_visits"] = df["anc_visits"].replace(999, np.nan)
df["maternal_hb_g_dl"] = pd.to_numeric(
df["maternal_hb_g_dl"], errors="coerce"
)
med = df.groupby("residence")["maternal_hb_g_dl"].transform("median")
df["maternal_hb_g_dl"] = df["maternal_hb_g_dl"].fillna(med)
df["anc_4plus"] = (df["anc_visits"] >= 4).fillna(False).astype(bool)
brief = df.groupby(
["residence", "wealth_quintile"], as_index=False
).agg(
n_households=("household_id", "count"),
stunting_pct=("child_stunted", "mean"),
anemia_pct=("maternal_anemia", "mean"),
anc4_pct=("anc_4plus", "mean"),
)
for col in ("stunting_pct", "anemia_pct", "anc4_pct"):
brief[col] = (brief[col] * 100).round(1)
return brief.sort_values(["residence", "wealth_quintile"]).reset_index(
drop=True
)
equity_brief = build_equity_brief(mch_raw)
print(equity_brief.to_string(index=False))Output:
residence wealth_quintile n_households stunting_pct anemia_pct anc4_pct
Rural Middle 71 4.2 43.7 60.6
Rural Poorer 86 22.1 33.7 37.2
Rural Poorest 91 31.9 48.4 20.9
Rural Richer 56 5.4 33.9 58.9
Rural Richest 52 5.8 19.2 76.9
Urban Middle 28 7.1 25.0 89.3
Urban Poorer 30 13.3 46.7 63.3
Urban Poorest 16 6.2 50.0 50.0
Urban Richer 35 5.7 28.6 77.1
Urban Richest 35 11.4 20.0 88.6Look at that single table—ready for a Lancet Global Health policy brief: only \(20.9\%\) of mothers in Rural + Poorest households achieve 4+ ANC visits (with \(31.9\%\) child stunting), compared to \(88.6\%\) ANC4+ coverage in Urban + Richest households!
18.5 Stage 5 — Guided “To-Do” Practice Labs
Open part_04_data_science_math/ch18_data_wrangling_surveys/02_guided_todos.ipynb in Google Colab, run Step 0 to activate sharukh-tutor, and build all six pure Pandas 3.x functions below. Pass each function name (without parentheses!) to tutor.check(...)—for example, tutor.check("ch18_todo_01", clean_mch_survey).
- To-Do 18.1 (Dirty Survey Cleaning —
clean_mch_survey(df)): Return a non-mutating copy normalizingresidencewith.str.strip().str.title(), convertinganc_visits == 999tonp.nan, and castingmaternal_hb_g_dlviapd.to_numeric(..., errors="coerce"). - To-Do 18.2 (Missingness Audit —
audit_missingness_table(df)): Return a DataFrame indexed by column name with integermissing_countand floatmissing_pct(rounded to 2 decimals), sorted bymissing_pctdescending then column name ascending. - To-Do 18.3 (Group-Median Imputation —
impute_group_median(df, value_col, group_col)): Return a non-mutating copy fillingNaNentries invalue_colusing per-group_colmedians via.groupby(group_col)[value_col].transform("median"). - To-Do 18.4 (Safe Relational Merge —
safe_merge_patient_labs(patients_df, labs_df)): Returnpd.merge(patients_df, labs_df, on="patient_id", how="left", validate="one_to_one")so unmatched patients stay withNaNand duplicate keys raisepd.errors.MergeError. - To-Do 18.5 (Split-Apply-Combine —
groupby_wealth_outcomes(mch_df)): Use named.agg()perwealth_quintile(kept as index) returningn_households,stunting_pct(mean * 100, 1 dec),anemia_pct(mean * 100, 1 dec), andmean_anc(2 dec). - To-Do 18.6 (Panel Rolling Average —
add_rolling_dengue_avg(epi_df, window=4)): Return a non-mutating copy sorted by["district", "year", "epi_week"]with columnrolling_dengueequal to the per-district rolling mean (window=window,min_periods=1, rounded to 2 decimals).
18.6 Stage 6 — Concept & Execution Trace Test (No Computer Allowed!)
Trace every wrangling question carefully on paper before checking Stage 8:
- MCAR vs. MAR vs. MNAR: In a maternal nutrition survey, rural clinics have \(12\%\) missing hemoglobin tests because of rural reagent stockouts while urban clinics have \(2\%\) missing. Assuming missingness depends only on observed
residence(not on a mother’s true anemia severity), which missing-data mechanism is this? - Sentinel Order-of-Operations Bug: Suppose a row has
anc_visits = 999(DHS"Don't know"). If you rundf["anc_4plus"] = df["anc_visits"] >= 4before replacing999withnp.nan, what boolean value doesanc_4pluswrongly receive? - Pandas 3.x Copy-on-Write Purity: Why should a wrangling function write
out = df.copy(); out["x"] = out["x"].fillna(0); return outinstead ofdf["x"].fillna(0, inplace=True)? - Strict Cast vs. Safe Coercion: What happens if you run
pd.Series(["10.5", "N/A", "12.0"]).astype(float)versuspd.to_numeric(pd.Series(["10.5", "N/A", "12.0"]), errors="coerce")? .transform("median")vs..median(): On a 500-row DataFrame with 2 residence categories (Rural,Urban), what is the length ofdf.groupby("residence")["maternal_hb_g_dl"].median()versusdf.groupby("residence")["maternal_hb_g_dl"].transform("median")?- Row-Explosion Arithmetic:
patientshas 4 unique IDs (P1..P4).labshas 5 rows whereP1appears twice andP2..P4appear once each. How many rows doespd.merge(patients, labs, on="patient_id", how="left")return withoutvalidate, and what happens withvalidate="one_to_one"? - Left Join vs. Inner Join Cohort Bias: In
patients(4 patients) left-joined tolabs(3 matching patients plus 1 orphan labP99), why doeshow="inner"distort cohort denominators whilehow="left"preserves them? as_index=Falsein Multi-Key GroupBy: What structural difference appears in the returned DataFrame when you passas_index=Falsetodf.groupby(["residence", "wealth_quintile"], as_index=False).agg(...)?- Cross-District Lag Leakage: A sorted DataFrame has Chattogram Weeks 1–52 followed immediately by Dhaka Weeks 1–52. If Chattogram Week 52 had
85dengue cases and you accidentally rundf["dengue_cases"].shift(1)without.groupby("district"), what value lands in Dhaka Week 1’sprev_week_cases? - Rolling Window
min_periods=1: For a single district whose first three weekly dengue counts are[20, 40, 60], what are the first three values of.rolling(window=4, min_periods=1).mean()versus.rolling(window=4).mean()(defaultmin_periods=4)?
18.7 Stage 7 — Chapter 18 Hands-On Coding Exam (100 Points)
Open part_04_data_science_math/ch18_data_wrangling_surveys/03_coding_exam.ipynb, implement all three functions, and run tutor.check_exam("ch18", exam_submissions) to earn your score out of 100 points.
18.7.1 Exam Task 18.1 (30 Points): build_clean_dhs_analytic_table(mch_df)
Build a non-mutating DHS cleaning function build_clean_dhs_analytic_table(mch_df):
- Copy
mch_dfwithout mutating the caller’s DataFrame. - Normalize
residencewith.str.strip().str.title(). - Replace
anc_visits == 999withnp.nan. - Convert
maternal_hb_g_dlto numeric (pd.to_numeric(..., errors="coerce")) and impute missingmaternal_hb_g_dlusing the per-residencemedian (computed after normalizingresidence!). - Add boolean column
anc_4plus = (out["anc_visits"] >= 4).fillna(False).astype(bool)(guaranteeingFalseforNaN/ former999).
18.7.2 Exam Task 18.2 (35 Points): equity_gap_by_residence_wealth(clean_mch_df)
Build equity_gap_by_residence_wealth(clean_mch_df):
- Group with
groupby(["residence", "wealth_quintile"], as_index=False). - Compute
n_households(row count),stunting_pct(child_stuntedmean \(\times 100\)),anemia_pct(maternal_anemiamean \(\times 100\)), andanc4_pct(anc_4plusmean \(\times 100\)), each percentage rounded to 1 decimal place. - Sort ascending by
["residence", "wealth_quintile"]and return without mutatingclean_mch_df.
18.7.3 Exam Task 18.3 (35 Points): prepare_epi_time_features(epi_df)
Build prepare_epi_time_features(epi_df):
- Return a non-mutating copy sorted by
["district", "year", "epi_week"]. - Add
incidence_per_100k:(dengue_cases / population) * 100_000, rounded to 2 decimal places. - Add
prev_week_cases: per-district 1-week lag (groupby("district")["dengue_cases"].shift(1)) with zero leakage across district boundaries. - Add
rolling_4w_cases: per-district 4-week rolling mean (window=4,min_periods=1, rounded to 2 decimal places) with zero leakage across district boundaries.
18.8 Stage 8 — Complete Annotated Solutions & Debugging Post-Mortem
18.8.1 A. Concept & Execution Trace Test Key
- MAR (Missing At Random): Missingness depends on an observed variable (
residence), not on the unobserved hemoglobin value itself—making per-residencemedian imputation principled. True! Because \(999 \ge 4\), computinganc_4plusbefore replacing999withnp.nanfalsely classifies unknown antenatal history as meeting the WHO 4+ visit target.- Creating
out = df.copy()and using direct assignment (out["x"] = ...) respects Pandas 3.x Copy-on-Write, preserves the caller’s raw data for auditability, and avoidsinplace=TruereturningNone. .astype(float)raisesValueError: could not convert string to float: 'N/A', whereaspd.to_numeric(..., errors="coerce")returnsSeries([10.5, NaN, 12.0], dtype=float64)..median()returns length2(one scalar per group);.transform("median")returns length500(one group median aligned to every original row index).- Without
validate, Pandas silently returns5rows (duplicatingP1!); withvalidate="one_to_one", Pandas immediately raisespd.errors.MergeError. how="inner"silently drops patients who lack a lab test, shrinking the cohort denominator and biasing prevalence estimates toward tested patients;how="left"keeps every enrolled patient (marking missing labs asNaN) while excluding orphan labP99.- With
as_index=False,residenceandwealth_quintileremain regular flat columns instead of becoming a two-levelMultiIndex. 85.0(Chattogram’s final week leaks into Dhaka’s Week 1!). Grouping by"district"first ensures Dhaka’s Week 1 receivesNaN.- With
min_periods=1:[20.0, 30.0, 40.0]; with defaultmin_periods=4:[NaN, NaN, NaN]because fewer than 4 observations are available in Weeks 1–3.
18.8.2 B. Annotated Solutions — Guided To-Dos (Mirrored in 02_guided_todos_SOLUTION.ipynb)
import numpy as np
import pandas as pd
# To-Do 18.1
def clean_mch_survey(df):
"""Return a cleaned copy of a dirty DHS/MCH household survey."""
out = df.copy()
out["residence"] = out["residence"].str.strip().str.title()
out["anc_visits"] = out["anc_visits"].replace(999, np.nan)
out["maternal_hb_g_dl"] = pd.to_numeric(
out["maternal_hb_g_dl"], errors="coerce"
)
return out
# To-Do 18.2
def audit_missingness_table(df):
"""Return column-level missing counts and percentages sorted neatly."""
counts = df.isna().sum().astype(int)
pcts = (counts / len(df) * 100).round(2)
audit = pd.DataFrame(
{"missing_count": counts, "missing_pct": pcts}
)
return audit.sort_index().sort_values(
"missing_pct", ascending=False, kind="mergesort"
)
# To-Do 18.3
def impute_group_median(df, value_col, group_col):
"""Fill NaNs in value_col using per-group medians without mutation."""
out = df.copy()
medians = out.groupby(group_col)[value_col].transform("median")
out[value_col] = out[value_col].fillna(medians)
return out
# To-Do 18.4
def safe_merge_patient_labs(patients_df, labs_df):
"""Left-join patients to labs with strict 1-to-1 key validation."""
return pd.merge(
patients_df,
labs_df,
on="patient_id",
how="left",
validate="one_to_one",
)
# To-Do 18.5
def groupby_wealth_outcomes(mch_df):
"""Aggregate stunting, anemia, and ANC outcomes by wealth quintile."""
out = mch_df.groupby("wealth_quintile").agg(
n_households=("child_stunted", "size"),
stunting_pct=("child_stunted", "mean"),
anemia_pct=("maternal_anemia", "mean"),
mean_anc=("anc_visits", "mean"),
)
out["stunting_pct"] = (out["stunting_pct"] * 100).round(1)
out["anemia_pct"] = (out["anemia_pct"] * 100).round(1)
out["mean_anc"] = out["mean_anc"].round(2)
return out
# To-Do 18.6
def add_rolling_dengue_avg(epi_df, window=4):
"""Add per-district rolling dengue mean without boundary leakage."""
out = epi_df.sort_values(["district", "year", "epi_week"]).copy()
out["rolling_dengue"] = (
out.groupby("district")["dengue_cases"]
.transform(lambda s: s.rolling(window=window, min_periods=1).mean())
.round(2)
)
return out18.8.3 C. Annotated Solutions — Chapter 18 Coding Exam (Mirrored in 03_coding_exam_SOLUTION.ipynb)
# Exam Task 18.1 (30 pts)
def build_clean_dhs_analytic_table(mch_df):
"""Clean DHS survey, impute Hb by residence, and flag anc_4plus."""
out = mch_df.copy()
out["residence"] = out["residence"].str.strip().str.title()
out["anc_visits"] = out["anc_visits"].replace(999, np.nan)
out["maternal_hb_g_dl"] = pd.to_numeric(
out["maternal_hb_g_dl"], errors="coerce"
)
medians = out.groupby("residence")["maternal_hb_g_dl"].transform(
"median"
)
out["maternal_hb_g_dl"] = out["maternal_hb_g_dl"].fillna(medians)
out["anc_4plus"] = (
(out["anc_visits"] >= 4).fillna(False).astype(bool)
)
return out
# Exam Task 18.2 (35 pts)
def equity_gap_by_residence_wealth(clean_mch_df):
"""Stratify stunting, anemia, and ANC4+ by residence and wealth."""
out = clean_mch_df.groupby(
["residence", "wealth_quintile"], as_index=False
).agg(
n_households=("child_stunted", "size"),
stunting_pct=("child_stunted", "mean"),
anemia_pct=("maternal_anemia", "mean"),
anc4_pct=("anc_4plus", "mean"),
)
for col in ("stunting_pct", "anemia_pct", "anc4_pct"):
out[col] = (out[col] * 100).round(1)
return out.sort_values(
["residence", "wealth_quintile"]
).reset_index(drop=True)
# Exam Task 18.3 (35 pts)
def prepare_epi_time_features(epi_df):
"""Engineer incidence, 1-week lag, and 4-week rolling dengue mean."""
out = epi_df.sort_values(["district", "year", "epi_week"]).copy()
out["incidence_per_100k"] = (
out["dengue_cases"] / out["population"] * 100_000
).round(2)
out["prev_week_cases"] = (
out.groupby("district")["dengue_cases"].shift(1)
)
out["rolling_4w_cases"] = (
out.groupby("district")["dengue_cases"]
.transform(lambda s: s.rolling(window=4, min_periods=1).mean())
.round(2)
)
return out18.8.4 D. Debugging Post-Mortem: Top 3 Chapter 18 Failure Modes
- Wrong Cleaning Order (
999 >= 4& Unnormalized Group Imputation): Thresholdinganc_visits >= 4before neutralizing999inflates ANC4+ coverage, and imputing hemoglobin before normalizing"rural"to"Rural"splits rural respondents across separate medians. Always follow: Normalize categories \(\rightarrow\) Neutralize sentinels \(\rightarrow\) Coerce & Impute \(\rightarrow\) Derive indicators. - Unvalidated Merges (Silent Row Explosion): Calling
pd.merge(patients, labs, on="patient_id", how="left")withoutvalidate="one_to_one"lets duplicate lab keys silently inflate sample sizes and double-count sick patients. - Global Lags/Rolling Windows on Panel Data: Calling
.shift(1)or.rolling(4).mean()directly on a multi-district DataFrame leaks one district’s final weeks into the next district’s Week 1. Always sort by[entity, time]and scope window operators inside.groupby(entity).
Your DHS maternal-child tables and weekly dengue panels are now clean, validated, and leak-free. Numbers in a printed table tell half the story—peer reviewers expect clear, colorblind-safe figures that surface disparities and epidemic waves at a glance. In Chapter 19, you will turn these exact wrangled DataFrames into publication-grade Matplotlib and Seaborn visualizations.


