← All Free Study Guides · Course: DS

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:

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):

DatasetExpected GrainPrimary KeyCommon Join Risk
conversion_visits.csvOne row per qualified visitvisit_idDuplicate visit_id inflates denominator.
conversion_outcomes.csvOne row per converted visitvisit_idMultiple outcome events per visit (e.g., trial + upgrade) multiply rows if joined without deduplicating!
product_margin.csvOne row per Period x Product Line(period, product_line)Summing margin % directly instead of SUM(gross_profit) / SUM(revenue).
delivery_performance.csvOne 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:

CountCorrectAfter the joinEffect
Visits (COUNT(*))34Denominator too large
Conversions (rows with an outcome)12Numerator too large, faster
Conversion rate33%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.

  1. Before the join: assert outcomes.visit_id.is_unique (or count rows per key and look at the maximum).
  2. Make the right table unique: deduplicate, or aggregate to one row per key (first payment date, number of events).
  3. 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:

PolicyExposure (years)ClaimsRows after the join
P11.022 (exposure 1.0 on each row)
P20.501
P31.011

!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

Our cleaning rules are:

  1. Trim whitespace and standardize text casing.
  2. Flag and remove invalid rows (deliveries <= 0, late_deliveries < 0 or blank, late_deliveries > deliveries, or missing hub).
  3. Deduplicate on (week, hub) keeping the validated record, and log the exact count removed.
  4. 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.

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):

  1. Duplicate Flag (Column E):
excel
   =COUNTIFS($A$2:A2, A2, $B$2:B2, B2) > 1

(Returns TRUE on the second occurrence of any (week, hub) pair.)

  1. Validity Flag (Column F):
excel
   =OR(TRIM(B2)="", C2<=0, ISBLANK(D2), D2<0, D2>C2)
  1. Keep Flag (Column G):
excel
   =AND(NOT(E2), NOT(F2))
  1. Clean Aggregation on a Summary tab using SUMIFS filtered on Keep = TRUE (never divide averages of rates!). The result is 0.106 (106 / 1,000):
excel
   =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

python
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

r
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)

sql
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:

MetricValueNotes
Raw rows8Original delivery_performance.csv extract
Invalid removed1Pending South row with 0 jobs and a blank late count excluded
Duplicates removed1Duplicate (Week 2, Central) retry row excluded
Clean rows analyzed63 hubs x 2 weeks (1,000 deliveries/week)
Week 1 Late Rate7.40%74 late / 1,000 deliveries
Week 2 Late Rate10.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:

ToolSafe Pattern for Missing ValuesDangerous Pattern to Avoid
ExcelLeave unsubmitted cells blank (""); AVERAGE ignores blanks.Typing 0 into blank cells so the sheet "looks neat".
PythonKeep np.nan / pd.NA; use .dropna() or .isna().sum() audit before filling.Blindly calling df.fillna(0) across the entire DataFrame.
RKeep NA; pass na.rm = TRUE explicitly only after auditing why NA exists.Global replace(is.na(.), 0) without checking column semantics.
SQLUse 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?"

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:

python
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 222
r
library(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 222

5. 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:

cohort_date+window_days≤extract_date\text{cohort\_date} + \text{window\_days} \le \text{extract\_date}

!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:

python
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())
r
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")
sql
-- 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

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: 50×1+5×2=6050 \times 1 + 5 \times 2 = 60, so the join returns 5,0605{,}060 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: (4+6+2+8)/4=5.0(4 + 6 + 2 + 8)/4 = 5.0. Filling it with zero gives 20/5=4.020/5 = 4.0, 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 30/600=5%30/600 = 5\% and 12/100=12%12/100 = 12\%, so the dashboard reports (5%+12%)/2=8.5%(5\% + 12\%)/2 = 8.5\%. The network rate pools the counts: (30+12)/(600+100)=42/700=6.0%(30 + 12)/(600 + 100) = 42/700 = 6.0\%. 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.

Related Exam DS Free Study Guides & Syllabus

Continue studying the Exam DS syllabus, formula sheets, and practice bank with these free companion modules:

Ready to test this topic under exam pressure?

Practice worked questions with step-by-step solutions and distractor trap diagnostics.

Open Interactive Version →