Data
DataIntermediate

Data Cleaning in Python and SQL: The Production Pipeline (and a 3M-Row Benchmark)

Most data cleaning tutorials stop at df.dropna(). In production, dirty CSVs hide sentinel strings ('N/A', '-'), mixed date formats, duplicate business keys, and silent type coercion. A 6-step pipeline with quarantine tables plus a 3M-row benchmark of Polars, DuckDB, and pandas.

Cover image: Data Cleaning in Python and SQL: The Production Pipeline (and a 3M-Row Benchmark)
Contents

Every data cleaning tutorial starts the same way: load a tidy sample CSV, run df.dropna(), call df.drop_duplicates(), and move on. Real production data breaks every assumption in that script within the first five minutes.

In practice, raw exports and event feeds arrive with "N/A" or "-" disguised as strings in numeric columns, mixed ISO (2026-10-15) and European (15/10/2026) dates, trailing whitespace (" berlin "), duplicate order IDs from webhook retries, and negative or 999999 sentinel amounts. If you let an eager parser guess types on ingest or silently drop broken rows, you trade visible errors for silent metric corruption.

The 6-Step Production Data Cleaning Pipeline

Instead of ad-hoc notebook fixes, production data cleaning works best as an ordered, idempotent pipeline. Order matters: trimming strings and converting sentinels before deduplicating prevents "berlin" and " BERLIN " from looking like distinct values.

Production data cleaning pipeline: ingest as strings, normalize sentinels to NULL, trim and parse types, deduplicate deterministically, validate domain rules, and split into clean vs quarantine tables
Routing failed rows to a quarantine table preserves auditability without polluting downstream BI or ML.
  1. Schema & safe ingest: Read dirty CSVs as strings (all_varchar=true in DuckDB, infer_schema=False in Polars, dtype=str in pandas) so one malformed cell on row 2,400,000 does not crash the entire load.
  2. Sentinel-to-NULL normalization: Convert "", "N/A", "null", "NULL", and "-" to true NULL before any aggregation or type cast. Leaving "-" in a text column breaks numeric parsing; replacing missing prices with 0 silently drags down averages.
  3. String standardization & safe parsing: Strip leading/trailing whitespace, normalize case on categorical fields (city, status), and use non-throwing casts (TRY_CAST / TRY_STRPTIME in DuckDB, strict=False in Polars, errors="coerce" in pandas).
  4. Deterministic deduplication: Calling drop_duplicates() without sorting keeps whichever row happened to appear first. Always partition by business key (order_id) and keep the newest record by updated_at DESC (with a deterministic tie-breaker).
  5. Domain & outlier validation: Enforce real invariants (amount > 0 AND amount <= 10000, valid order_date, non-null primary keys). Statistical IQR or z-score filters help spot anomalies, but hard business bounds catch corrupt sensor or billing payloads reliably.
  6. Clean vs. quarantine split: Write passing rows to your clean Silver table and route rejected rows—with the raw values and a failure_reason—into a quarantine (dead-letter) table so upstream breakages trigger alerts instead of disappearing.

Data cleaning repairs structural and domain defects while keeping the original row grain intact. Aggregating, joining, and reshaping belong downstream in data transformation—never mix broken-row cleanup with business KPIs in one opaque query.

Benchmark: Polars vs. DuckDB vs. pandas on 3M Dirty Rows

To measure what each engine actually costs when cleaning messy data at scale, we generated a deterministic 3,000,000-row dirty CSV (197.6 MB) containing whitespace/casing mismatches, "N/A"/"null"/"-" sentinels, mixed %Y-%m-%d and %d/%m/%Y dates plus invalid dates, 10% duplicate order_ids, and negative/outlier amounts.

Every engine ran the exact same 5-step cleaning and deduplication logic in an isolated process under /usr/bin/time -l (4 runs each, median of the last 3), and we verified that all three produced the exact same output: 808,467 clean rows and sum(amount) = 209,827,034.50.

Benchmark: Polars vs. DuckDB vs. pandas on 3M Dirty Rows
Engine Median Wall Time Speedup vs. pandas Peak RSS Memory Memory vs. pandas Cleaned Output Verified
Polars 1.36.1 (scan_csv lazy) 0.19 s 23.9x faster 1,148 MB 1.24x less 808,467 rows · 209,827,034.50
DuckDB 1.4.5 (read_csv_auto SQL) 0.32 s 14.2x faster 510 MB 2.80x less 808,467 rows · 209,827,034.50
pandas 2.3.3 (read_csv) 4.55 s 1.0x (baseline) 1,426 MB 1.0x (baseline) 808,467 rows · 209,827,034.50
Data cleaning benchmark on 3M dirty rows: Polars finishes in 0.19s, DuckDB uses only 510 MB peak RSS, and pandas takes 4.55s and 1,426 MB
Polars wins on raw speed; DuckDB wins on peak memory and lets SQL teams keep cleaning declarative.

The numbers split cleanly into two distinct winners depending on your bottleneck:

  • Polars is the fastest option at 0.19 s—nearly 24x faster than pandas—because its Rust engine executes lazy expressions and string/date parsing in parallel across cores without Python object overhead.
  • DuckDB is nearly as fast (0.32 s, 14.2x faster than pandas) while using only 510 MB peak RSS—less than half of Polars and 2.8x less RAM than pandas—making it ideal for memory-capped containers, CI runners, and SQL-first teams.
  • pandas took 4.55 s and 1,426 MB for 197.6 MB of CSV because Python string objects (dtype=str / object) inflate memory ~7x over raw file size. For more on how DuckDB and Polars compare across broader analytical workloads, see DuckDB Explained vs SQLite, Polars, and BigQuery.

Production Code: The Exact Cleaning Pipeline in SQL and Python

Below is the core logic tested in the benchmark, written cleanly in DuckDB SQL and Polars so you can drop either into a scheduled job or dbt/Python pipeline.

Option 1: DuckDB SQL (Best Memory Efficiency & Declarative Rules)

DuckDB’s QUALIFY ROW_NUMBER() lets you deduplicate in one readable CTE chain without self-joins, and TRY_CAST / TRY_STRPTIME turn corrupt strings into NULL instead of aborting the query:

clean_orders.sql
WITH raw AS (
SELECT
CAST(order_id AS BIGINT) AS order_id,
CAST(customer_id AS BIGINT) AS customer_id,
NULLIF(TRIM(city), '') AS city_raw,
NULLIF(LOWER(TRIM(status)), '') AS status_raw,
TRY_CAST(NULLIF(TRIM(amount), '') AS DOUBLE) AS amount,
COALESCE(
TRY_STRPTIME(NULLIF(TRIM(order_date), ''), '%Y-%m-%d'),
TRY_STRPTIME(NULLIF(TRIM(order_date), ''), '%d/%m/%Y')
) AS order_date,
updated_at
FROM read_csv_auto('dirty_orders.csv', all_varchar=true)
),
normalized AS (
SELECT
order_id,
customer_id,
CASE
WHEN city_raw IS NULL OR UPPER(city_raw) IN ('N/A', 'NULL', '-') THEN NULL
ELSE UPPER(SUBSTR(city_raw, 1, 1)) || LOWER(SUBSTR(city_raw, 2))
END AS city,
CASE
WHEN status_raw IS NULL OR status_raw IN ('n/a', 'null', '-') THEN NULL
ELSE status_raw
END AS status,
amount,
order_date,
updated_at
FROM raw
)
SELECT *
FROM normalized
WHERE city IS NOT NULL
AND status IS NOT NULL
AND order_date IS NOT NULL
AND amount > 0
AND amount <= 10000
QUALIFY ROW_NUMBER() OVER (
PARTITION BY order_id ORDER BY updated_at DESC, customer_id DESC
) = 1;

Option 2: Polars Lazy API (Fastest Python Execution)

Using pl.scan_csv(..., infer_schema=False) keeps memory bounded until .collect() and lets Polars push filters and projections down before sorting for deduplication:

clean_orders_polars.py
import polars as pl
SENTINELS = ["", "N/A", "null", "NULL", "-"]
clean_df = (
pl.scan_csv("dirty_orders.csv", infer_schema=False)
.with_columns([
pl.col("order_id").cast(pl.Int64),
pl.col("customer_id").cast(pl.Int64),
pl.col("city").str.strip_chars().alias("city_trim"),
pl.col("status").str.strip_chars().str.to_lowercase().alias("status_clean"),
pl.col("amount").str.strip_chars().cast(pl.Float64, strict=False),
pl.coalesce([
pl.col("order_date").str.strip_chars().str.to_date("%Y-%m-%d", strict=False),
pl.col("order_date").str.strip_chars().str.to_date("%d/%m/%Y", strict=False),
]).alias("order_date"),
])
.filter(
(~pl.col("city_trim").is_in(SENTINELS))
& (~pl.col("status_clean").is_in(["", "n/a", "null", "-"]))
& pl.col("order_date").is_not_null()
& (pl.col("amount") > 0)
& (pl.col("amount") <= 10000)
)
.with_columns(pl.col("city_trim").str.to_titlecase().alias("city"))
.sort(["order_id", "updated_at", "customer_id"], descending=[False, True, True])
.unique(subset=["order_id"], keep="first")
.collect()
)

Quick Reference: Common Cleaning Operations Side by Side

Quick Reference: Common Cleaning Operations Side by Side
Defect DuckDB SQL Polars pandas
Trim & lowercase LOWER(TRIM(col)) pl.col("col").str.strip_chars().str.to_lowercase() df["col"].str.strip().str.lower()
Sentinel → NULL NULLIF(TRIM(col), 'N/A') pl.when(pl.col("col").is_in(["N/A", "-"])).then(None) df["col"].replace(["N/A", "-"], pd.NA)
Safe numeric cast TRY_CAST(col AS DOUBLE) pl.col("col").cast(pl.Float64, strict=False) pd.to_numeric(df["col"], errors="coerce")
Multi-format date COALESCE(TRY_STRPTIME(c, '%Y-%m-%d'), TRY_STRPTIME(c, '%d/%m/%Y')) pl.coalesce([pl.col("c").str.to_date("%Y-%m-%d", strict=False), ...]) d1.fillna(d2) via pd.to_datetime(..., errors="coerce")
Latest-wins dedupe QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY ts DESC) = 1 .sort(["id", "ts"], descending=[False, True]).unique(["id"], keep="first") .sort_values(["id", "ts"], ascending=[True, False]).drop_duplicates(["id"])

Common Data Cleaning Mistakes That Break Production

  • Calling df.dropna() globally: A single NULL in an optional coupon_code column silently deletes valid paid orders. Always validate NOT NULL per required column.
  • Imputing missing numbers with 0 or global mean without a flag: Replacing missing prices with 0 skews revenue medians; filling missing timestamps with now() fabricates recency. Keep NULL unless a domain rule explicitly defines a default, and add an is_imputed boolean if you impute for ML.
  • Deduplicating before normalizing keys: Emails like "Alice@Example.com " and "alice@example.com" only collapse into one customer after TRIM and LOWER.
  • Ignoring ownership and contracts: Cleaning scripts in downstream pipelines are a band-aid if upstream producers keep changing column formats. Pair automated cleaning with schema contracts and clear ownership as outlined in Data Governance on GCP.

The Bottom Line

Effective data cleaning is not a collection of one-line pandas tricks—it is a deterministic boundary between messy external inputs and trusted analytics. Read raw files as strings, convert sentinels to NULL, deduplicate with an explicit timestamp tie-breaker, and quarantine rejected rows instead of hiding them. Once your files pass a few hundred thousand rows, moving that pipeline from pandas to Polars (0.19 s) or DuckDB (0.32 s, 510 MB RAM) eliminates memory spikes while keeping the code cleaner.

DuckDB Explained vs SQLite, Polars, and BigQuery

Frequently asked questions

What is data cleaning and why does it matter?

Data cleaning (or data cleansing) is the process of detecting and fixing structural, formatting, and domain errors in raw datasets—such as duplicate records, sentinel strings like 'N/A', mixed date formats, leading whitespace, and impossible numeric outliers—before analytics or machine learning models consume them. Skipping it causes silent metric drift, failed joins, and biased models.

What are the core steps of data cleaning?

A reliable production data cleaning pipeline follows six steps: (1) ingest raw data as strings to avoid parser crashes, (2) normalize sentinel strings ('', 'N/A', 'null', '-') to NULL, (3) trim whitespace, standardize casing, and parse numbers/dates safely, (4) deduplicate deterministically by business key and latest timestamp, (5) validate domain rules and outliers, and (6) route invalid rows to a quarantine table instead of silently dropping them.

Which is faster for data cleaning in Python: pandas, Polars, or DuckDB?

On a 3,000,000-row dirty CSV (197.6 MB) running the exact same normalization, date parsing, domain filtering, and deduplication pipeline, lazy Polars 1.36.1 finished in 0.19 s (1,148 MB RSS), DuckDB 1.4.5 finished in 0.32 s (510 MB RSS), and pandas 2.3.3 took 4.55 s (1,426 MB RSS). Polars wins on raw speed (23.9x faster than pandas), while DuckDB uses less than half the memory of Polars and lets you write the pipeline in SQL.

How should you handle missing values without distorting metrics?

First distinguish true missing values from string sentinels ('N/A', '-', 'unknown', 0). Never blindly call df.dropna() or fillna(0) on financial or sensor columns—zeroes pull down averages and dropna() can delete entire cohorts when only an optional field is missing. Keep NULL where absence is meaningful, impute only with documented rules, and quarantine rows missing required keys.

What is the difference between data cleaning and data transformation?

Data cleaning repairs defects in existing records (fixing types, trimming strings, resolving duplicates, quarantining invalid values) while preserving the original entity grain. Data transformation changes structure or grain—such as joining tables, pivoting, computing rolling aggregates, or building star-schema fact tables—on top of already-clean inputs.

When should you still use pandas for data cleaning?

pandas remains practical for small datasets under roughly 100,000 rows, exploratory notebook work, or workflows tightly coupled to scikit-learn and legacy Python libraries. Once CSV or Parquet inputs reach millions of rows or run inside scheduled memory-constrained containers, switching to Polars or DuckDB cuts runtime by an order of magnitude.

Why use a quarantine table instead of dropping bad rows?

Silently filtering out malformed rows hides upstream schema drift, broken webhook payloads, or regional date-format changes until a stakeholder notices missing revenue weeks later. Writing rejected rows alongside a failure_reason column lets engineers inspect, alert on, and replay fixed records.

From the community

Discussion on Mastodon & Bluesky

Replies to this article from the open web, pulled in live. No ads, no tracking scripts.

Loading replies …
Reply on MastodonReply on Bluesky

Reply there — it shows up here automatically.

ENDE