Module 2: Multi-Tool Data Preparation and Quality Audits
Declare the grain, log every exclusion, and make Excel, Python, R and SQL agree
1. Why Data Preparation Is 60% of Data Storytelling
A polished executive chart built on un-audited data is worse than an ugly chart: it delivers false certainty with high visual authority. In real-world analytics, raw CSV exports and database extracts routinely contain:
- Duplicate submission rows caused by retry logic or double-clicks (
delivery_performance.csvincludes an intentional duplicate). - Incomplete or placeholder rows (zero or negative counts like
-99, blank fields, "pending" records, test accounts, or missing regions). - Unmatched foreign keys where an outcome row references a visit or customer ID missing from the master table.
- Immature / right-censored records whose observation window has not closed yet.
The professional standard is tool-agnostic discipline: whether your organization runs Excel, SQL, Python, or R, your cleaning script must enforce the exact same deterministic assertions and log every excluded row.
2. Grain, Keys, and Join Integrity
Before writing a VLOOKUP, MERGE, left_join, or LEFT JOIN, declare the grain (what one row represents):
| Dataset | Expected Grain | Primary Key | Common Join Risk |
|---|---|---|---|
conversion_visits.csv | One row per qualified visit | visit_id | Duplicate visit_id inflates denominator. |
conversion_outcomes.csv | One row per converted visit | visit_id | Multiple outcome events per visit (e.g., trial + upgrade) multiply rows if joined without deduplicating! |
product_margin.csv | One row per Period x Product Line | (period, product_line) | Summing margin % directly instead of SUM(gross_profit) / SUM(revenue). |
delivery_performance.csv | One row per Hub x Week | (period, hub) | Duplicate (period, hub) rows, padded hub names (" South "), pending rows with zero jobs. |
!Three visits joined to outcomes where one visit has two outcome rows
What happens row by row. A join returns one output row for every matching pair of rows. V1 and V3 have no outcome, so each keeps one row with NULL. V2 matches two outcome rows, so it appears twice. Both counts then go wrong at once:
| Count | Correct | After the join | Effect |
|---|---|---|---|
Visits (COUNT(*)) | 3 | 4 | Denominator too large |
| Conversions (rows with an outcome) | 1 | 2 | Numerator too large, faster |
| Conversion rate | 33% | 50% | Overstated by half |
Because the duplicated visit is always a converting visit, the numerator grows proportionally more than the denominator: join inflation nearly always overstates conversion.
The three-line habit.
- Before the join:
assert outcomes.visit_id.is_unique(or count rows per key and look at the maximum). - Make the right table unique: deduplicate, or aggregate to one row per key (
first payment date,number of events). - After the join:
assert len(merged) == len(visits).
Example: Exposure counted twice in a policy-claims join
Three motor policies, joined to the claims table before computing frequency:
| Policy | Exposure (years) | Claims | Rows after the join |
|---|---|---|---|
| P1 | 1.0 | 2 | 2 (exposure 1.0 on each row) |
| P2 | 0.5 | 0 | 1 |
| P3 | 1.0 | 1 | 1 |
- Correct frequency: claims per policy-year.
- After the join, P1's exposure is summed twice: , about 29% too low.
- The fix: aggregate claims to one row per policy (count and amount) before joining, then assert that the row count still equals the number of policies.
!The policy with two claims appears twice after the join, inflating exposure
Why it is easy to miss. Nothing errors and every individual row is correct: P1 really has exposure 1.0 and really had claim C1 and claim C2. The mistake is only in the sum: exposure is a property of the policy, and the join copied it onto each claim. Any column that belongs to the "one" side of a one-to-many join must never be summed after the join. In this example the bias is downwards, so the portfolio would look safer than it is and could be under-priced.
3. Primary Excel Walkthrough & Optional Code Track
Data: delivery_performance.csv, conversion_visits.csv and conversion_outcomes.csv
The raw file has 8 rows and columns period, hub, eligible_jobs, late_jobs, source_status. In the code below these are renamed to week, hub, deliveries, late_deliveries so the logic reads naturally. Two rows are bad:
!The eight raw rows with the audit flag for each
- Row 7 repeats
(Week 2, Central)exactly: a retry of the same upload. - Row 8 is a
pendingplaceholder for South: the hub name has spaces around it, eligible jobs are 0 and the late count is blank.
Our cleaning rules are:
- Trim whitespace and standardize text casing.
- Flag and remove invalid rows (
deliveries <= 0,late_deliveries < 0or blank,late_deliveries > deliveries, or missinghub). - Deduplicate on
(week, hub)keeping the validated record, and log the exact count removed. - Compute
late_rate = late_deliveries / deliveries.
Order matters. Remove invalid rows before deduplicating. Otherwise row 8, once its hub name is trimmed to "South", could be kept as the "first" South row for Week 2 and the real South row dropped as its duplicate.
!Rows removed at each step and the effect of the duplicate on the Week 2 late rate
Why it matters for the headline. The invalid row adds no jobs, so it does not change the rate, but it would add a fourth hub to a count of hubs. The duplicate does change the rate: Central's week had a high late rate (48 of 320), so counting it twice pushes Week 2 from 10.6% to 11.7%, more than a point of pure error.
Primary Path: Excel / Google Sheets (Recommended)
In a dedicated Raw_Audit tab next to the raw columns (A:D = period, hub, eligible_jobs, late_jobs; in a clean copy, use =TRIM(B2) for the hub):
- Duplicate Flag (Column E):
=COUNTIFS($A$2:A2, A2, $B$2:B2, B2) > 1(Returns TRUE on the second occurrence of any (week, hub) pair.)
- Validity Flag (Column F):
=OR(TRIM(B2)="", C2<=0, ISBLANK(D2), D2<0, D2>C2)- Keep Flag (Column G):
=AND(NOT(E2), NOT(F2))- Clean Aggregation on a
Summarytab usingSUMIFSfiltered onKeep = TRUE(never divide averages of rates!). The result is 0.106 (106 / 1,000):
=SUMIFS(Raw_Audit!$D$2:$D$9, Raw_Audit!$A$2:$A$9, "Week 2", Raw_Audit!$G$2:$G$9, TRUE) / SUMIFS(Raw_Audit!$C$2:$C$9, Raw_Audit!$A$2:$A$9, "Week 2", Raw_Audit!$G$2:$G$9, TRUE)Option B: Python (pandas) Reproducible Pipeline
import pandas as pd
raw = pd.read_csv("delivery_performance.csv").rename(
columns={"period": "week", "eligible_jobs": "deliveries", "late_jobs": "late_deliveries"}
)
raw["hub"] = raw["hub"].astype(str).str.strip()
raw["week"] = raw["week"].astype(str).str.strip()
# 1. Separate invalid placeholder / impossible rows
invalid_mask = (
raw["hub"].isin(["", "nan", "None"])
| (raw["deliveries"] <= 0)
| raw["late_deliveries"].isna()
| (raw["late_deliveries"] < 0)
| (raw["late_deliveries"] > raw["deliveries"])
)
invalid_rows = raw[invalid_mask]
valid = raw[~invalid_mask].copy()
# 2. Deduplicate on grain (week, hub)
dup_mask = valid.duplicated(subset=["week", "hub"], keep="first")
dup_rows = valid[dup_mask]
clean = valid[~dup_mask].copy()
# 3. Assertions (fail loudly if grain is still broken)
assert clean.duplicated(subset=["week", "hub"]).sum() == 0, "Grain violation!"
assert (clean["deliveries"] > 0).all(), "Non-positive deliveries remain!"
clean["late_rate"] = clean["late_deliveries"] / clean["deliveries"]
print(f"Raw rows: {len(raw)} | Invalid removed: {len(invalid_rows)} | Duplicates removed: {len(dup_rows)} | Clean rows: {len(clean)}")Option C: R (dplyr / readr) Reproducible Pipeline
library(dplyr)
library(readr)
library(stringr)
raw <- read_csv("delivery_performance.csv", show_col_types = FALSE) |>
rename(week = period, deliveries = eligible_jobs, late_deliveries = late_jobs) |>
mutate(
hub = str_trim(as.character(hub)),
week = str_trim(as.character(week))
)
# 1. Audit invalid records
valid <- raw |>
filter(!is.na(hub), hub != "", deliveries > 0, !is.na(late_deliveries),
late_deliveries >= 0, late_deliveries <= deliveries)
invalid_count <- nrow(raw) - nrow(valid)
# 2. Deduplicate on grain (week, hub)
clean <- valid |>
distinct(week, hub, .keep_all = TRUE) |>
mutate(late_rate = late_deliveries / deliveries)
dup_count <- nrow(valid) - nrow(clean)
# 3. Grain assertion
stopifnot(nrow(clean) == nrow(distinct(clean, week, hub)))
cat(sprintf("Raw: %d | Invalid: %d | Duplicates: %d | Clean: %d\n",
nrow(raw), invalid_count, dup_count, nrow(clean)))Option D: SQL (PostgreSQL / DuckDB / BigQuery Pattern)
WITH standardized AS (
SELECT
TRIM(period) AS week,
TRIM(hub) AS hub,
eligible_jobs AS deliveries,
late_jobs AS late_deliveries,
ROW_NUMBER() OVER (
PARTITION BY TRIM(period), TRIM(hub)
ORDER BY eligible_jobs DESC
) AS rn
FROM raw_delivery_performance
WHERE hub IS NOT NULL
AND TRIM(hub) <> ''
AND eligible_jobs > 0
AND late_jobs IS NOT NULL
AND late_jobs >= 0
AND late_jobs <= eligible_jobs
)
SELECT
week,
hub,
deliveries,
late_deliveries,
ROUND(1.0 * late_deliveries / deliveries, 4) AS late_rate
FROM standardized
WHERE rn = 1;Expected Output (All Four Tools)
Regardless of whether you run Excel, Python, R, or SQL, your audit log and cleaned summary must reconcile to these exact figures:
| Metric | Value | Notes |
|---|---|---|
| Raw rows | 8 | Original delivery_performance.csv extract |
| Invalid removed | 1 | Pending South row with 0 jobs and a blank late count excluded |
| Duplicates removed | 1 | Duplicate (Week 2, Central) retry row excluded |
| Clean rows analyzed | 6 | 3 hubs x 2 weeks (1,000 deliveries/week) |
| Week 1 Late Rate | 7.40% | 74 late / 1,000 deliveries |
| Week 2 Late Rate | 10.60% | 106 late / 1,000 deliveries |
!Four tool pipelines reconciling to one table
How to use the reconciliation. Run at least two tools on the same raw file the first time you build a pipeline. If Excel says 6 clean rows and SQL says 7, one of them is applying a rule the other is not (often trimming, or how blanks compare). Fix the rule in both, then keep the expected-output table next to the code as a regression test: if a future extract changes these numbers, you want to know why.
4. Handling Missing Values (NULL / NA) vs. Zero (0)
Treating NULL as 0 is one of the most damaging silent bugs in business reporting:
- True Zero (
0): A hub operated all week and recorded0late deliveries, or a customer visited and made0purchases. This belongs in the denominator of an average. - Missing (
NULL/NA): A sensor went offline, a branch failed to submit Tuesday's file, or a survey respondent skipped a question. ReplacingNULLwith0artificially drags down averages and inflates failure/zero counts.
| Tool | Safe Pattern for Missing Values | Dangerous Pattern to Avoid |
|---|---|---|
| Excel | Leave unsubmitted cells blank (""); AVERAGE ignores blanks. | Typing 0 into blank cells so the sheet "looks neat". |
| Python | Keep np.nan / pd.NA; use .dropna() or .isna().sum() audit before filling. | Blindly calling df.fillna(0) across the entire DataFrame. |
| R | Keep NA; pass na.rm = TRUE explicitly only after auditing why NA exists. | Global replace(is.na(.), 0) without checking column semantics. |
| SQL | Use COALESCE(col, 0) only for additive counts where absence means zero (e.g., left-joined conversions). | COALESCE(score, 0) on survey ratings or unit costs. |
!Average late deliveries with a missing hub left out and with the missing hub filled as zero
Read the two panels. Hub C did not send its file. In panel A the gap stays a gap: the average of the four hubs that reported is 5.0. In panel B fillna(0) turns the missing file into a hub with a perfect week, and the average falls to 4.0. Nothing improved; a file was lost. The same trap in insurance: a branch whose claims extract failed shows zero claims and the best loss ratio in the company.
A question that settles each case. Ask: "If I had perfect information, could this value be zero?"
- A visit with no matching outcome row: yes, it converted zero times. Fill with 0.
- A hub with no file: the late count exists, we just do not have it. Keep it missing and footnote it.
- A claim amount not yet assessed: it is certainly not zero. Keep it missing, or use a case estimate.
Left-Joining Outcomes Safely
Data: visit_level.csv (2,000 visits, one row per visit_id) and visit_outcomes.csv (240 outcome rows for 222 converting visits: 18 visits have a second "retry" row).
When joining a visits table to an outcomes table, an unmatched visit genuinely had 0 conversions, so COALESCE / fillna(0) on the conversion indicator only is appropriate, provided outcomes is first deduplicated to 1 row per visit_id:
import pandas as pd
visits = pd.read_csv("visit_level.csv")
outcomes = pd.read_csv("visit_outcomes.csv").drop_duplicates(subset=["visit_id"])
merged = visits.merge(outcomes[["visit_id", "converted"]], on="visit_id", how="left")
merged["converted"] = merged["converted"].fillna(0).astype(int)
assert len(merged) == len(visits), "Row count changed after left join!"
print(len(merged), merged["converted"].sum()) # 2000 222library(dplyr)
library(readr)
visits <- read_csv("visit_level.csv", show_col_types = FALSE)
outcomes <- read_csv("visit_outcomes.csv", show_col_types = FALSE) |>
distinct(visit_id, .keep_all = TRUE)
merged <- visits |>
left_join(outcomes |> select(visit_id, converted), by = "visit_id") |>
mutate(converted = coalesce(converted, 0L))
stopifnot(nrow(merged) == nrow(visits))
cat(nrow(merged), sum(merged$converted), "\n") # 2000 2225. Right-Censoring and Cohort Maturity Audits
Whenever you measure an event that takes time to occur (trial conversion within 14 days, insurance claim reporting within 30 days, order delivery within 5 days), records near the extract date are right-censored.
Suppose your extract date is extract_date = 2026-05-01 and your target window is window_days = 14. Every cohort must satisfy:
!Signup cohorts with their 14-day windows against the extract date
Read the chart. Each bar is a signup cohort's 14-day window. Green bars end on or before May 1, so the whole window has been observed. Red bars cross the extract date: the dotted part is time that has not happened yet. Rearranging the rule gives the cut-off directly: $\text{cohort\_date} \le \text{extract\_date} - \text{window\_days} = $ April 17.
What to do with the red cohorts. Do not delete them from the data, only from the comparison. Report them separately as an early indicator with a shorter window (for example 3-day conversion), and re-run the 14-day figure once they mature.
The same visit file has a visit_date column (April 2026), so the maturity filter can be run directly:
import pandas as pd
visits = pd.read_csv("visit_level.csv")
extract_date = pd.Timestamp("2026-05-01")
visits["visit_date"] = pd.to_datetime(visits["visit_date"])
mature_visits = visits[visits["visit_date"] <= extract_date - pd.Timedelta(days=14)].copy()
print(len(visits), len(mature_visits), mature_visits["visit_date"].max().date())library(dplyr)
library(readr)
visits <- read_csv("visit_level.csv", show_col_types = FALSE)
extract_date <- as.Date("2026-05-01")
mature_visits <- visits |>
filter(as.Date(visit_date) <= extract_date - 14)
cat(nrow(visits), nrow(mature_visits), "\n")-- visit_level loaded from visit_level.csv, with visit_date as a DATE
SELECT *
FROM visit_level
WHERE visit_date <= DATE '2026-05-01' - INTERVAL '14 days';6. The 5-Line Data Audit Footnote Standard
Never hide data exclusions. Every decision slide or memo should carry a compact, verifiable audit footnote (or appendix table) so no executive can ambush you with "Wait, why does your total differ from the raw finance export?"
Example Audit Footnote:
Source:
delivery_performance.csv(Weeks 1 to 2). Raw extract: 8 rows. Excluded 1 pending placeholder row (South, 0 jobs, no late count) and 1 duplicate(Week 2, Central)entry; 6 validated hub-week records analyzed (2,000 total deliveries).
Why five parts. Each part answers a question an executive can ask: where from? (source), which period?, how many did you start with? (raw count, which they can check against their own export), what did you drop and why?, and what is left? A reader who can reconcile your number to theirs in thirty seconds stops questioning the data and starts discussing the decision.
7. Review checklist
- [ ] Grain declared: Primary key of every input table is verified unique (or explicitly aggregated/deduplicated first).
- [ ] Invalid rows isolated: Negative counts, impossible rates (
> 100%), and blank keys are logged and removed before aggregation. - [ ] Missing vs. zero separated:
NULL/NAis never blindly turned into0unless representing an unmatched outer-join event count. - [ ] Maturity filter applied: Right-censored cohorts are excluded before calculating time-window rates.
- [ ] Audit trail written: Raw vs. clean row counts are documented in a reproducible script and slide footnote.
8. Practice problems
Problem 1: Counting rows after a join
A visits table has 5,000 rows with unique visit_id. The outcomes table has 700 rows covering 640 distinct visit_id values: 585 appear once, 50 appear twice and 5 appear three times. How many rows does a left join of visits to outcomes return, and what should be done first?
Solution: Each visit with one outcome row keeps one row; a visit with two outcome rows becomes two rows (one extra), and a visit with three becomes three (two extra). Extra rows: , so the join returns rows. Deduplicate (or aggregate) the outcomes to one row per visit_id before joining, then assert that the joined table still has 5,000 rows.
Problem 2: Missing is not zero
Five hubs report late deliveries for one week: 4, 6, missing, 2 and 8. The missing hub failed to send its file. What is the correct average, and what average would a fillna(0) produce?
Solution: The missing hub has no measurement, so it is left out: . Filling it with zero gives , which understates late deliveries by 20% and reports a hub that never reported as perfect. The audit footnote should say that one hub's file is missing.
Problem 3: Averaging rates or pooling counts
Hub A had 30 late deliveries out of 600; Hub B had 12 late out of 100. A dashboard reports the network late rate as the average of the two hub rates. What does it report, what is the correct network rate, and why do they differ?
Solution: The hub rates are and , so the dashboard reports . The network rate pools the counts: . Averaging rates gives the small hub the same weight as the large one. For a network figure, always divide total events by total volume.
Problem 4: Writing the audit footnote
A raw extract of policy-month records has 12 rows. One row belongs to a test account and two rows duplicate the key (month, branch). Write a one-line audit footnote for the slide.
Solution: "Source: branch extract, March to May. Raw extract: 12 rows. Excluded 1 test-account row and 2 duplicate (month, branch) rows; 9 validated branch-month records analyzed." It names the source and the period, the raw count, every exclusion with its reason, and the final count, so anyone can reconcile the slide to the raw file.
Problem 5: Why assert after every join
A colleague says the row-count check after a join is unnecessary "because the join code has not changed in months". Give two reasons to keep the assertion.
Solution: First, the data change even when the code does not: a new outcome type, a retry event or a duplicated upload can create several rows per key and silently inflate counts. Second, the check fails loudly at the moment the problem appears, instead of letting a wrong conversion rate reach an executive slide, where it is far more expensive to correct. The assertion costs one line and protects every number downstream.