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.

- Schema & safe ingest: Read dirty CSVs as strings (
all_varchar=truein DuckDB,infer_schema=Falsein Polars,dtype=strin pandas) so one malformed cell on row 2,400,000 does not crash the entire load. - Sentinel-to-
NULLnormalization: Convert"","N/A","null","NULL", and"-"to trueNULLbefore any aggregation or type cast. Leaving"-"in a text column breaks numeric parsing; replacing missing prices with0silently drags down averages. - String standardization & safe parsing: Strip leading/trailing whitespace, normalize case on categorical fields (
city,status), and use non-throwing casts (TRY_CAST/TRY_STRPTIMEin DuckDB,strict=Falsein Polars,errors="coerce"in pandas). - 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 byupdated_at DESC(with a deterministic tie-breaker). - Domain & outlier validation: Enforce real invariants (
amount > 0 AND amount <= 10000, validorder_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. - 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.
| 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 |

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:
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 normalizedWHERE city IS NOT NULL AND status IS NOT NULL AND order_date IS NOT NULL AND amount > 0 AND amount <= 10000QUALIFY 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:
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
| 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 singleNULLin an optionalcoupon_codecolumn silently deletes valid paid orders. Always validateNOT NULLper required column. - Imputing missing numbers with
0or global mean without a flag: Replacing missing prices with0skews revenue medians; filling missing timestamps withnow()fabricates recency. KeepNULLunless a domain rule explicitly defines a default, and add anis_imputedboolean if you impute for ML. - Deduplicating before normalizing keys: Emails like
"Alice@Example.com "and"alice@example.com"only collapse into one customer afterTRIMandLOWER. - 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.







From the community
Discussion on Mastodon & Bluesky
Replies to this article from the open web, pulled in live. No ads, no tracking scripts.
Reply there — it shows up here automatically.