---
title: "Data Cleaning in Python and SQL: The Production Pipeline (and a 3M-Row Benchmark)"
description: "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."
author: Aleksei Aleinikov
date: 2026-11-30
lang: en
tags: [data-cleaning, data-cleaning-python, duckdb, polars, python, sql]
canonical: https://www.alekseialeinikov.com/en/blog/topics/data/data-cleaning-python-sql-guide
source: alekseialeinikov.com
---

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

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](https://media.alekseialeinikov.com/data/d4c81e9a3b72/data-cleaning-pipeline-steps-1200.f382e54a9730a55e.webp "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.

> [!KEY]
> 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_id`s, 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 |

![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](https://media.alekseialeinikov.com/data/d4c81e9a3b72/data-cleaning-benchmark-1200.8c076af49254e6fc.webp "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](https://www.alekseialeinikov.com/en/blog/topics/data/duckdb-explained-vs-sqlite-polars-bigquery).

> [!NOTE]
> **Reproducibility:** Full generator and benchmark scripts are in [data-cleaning-benchmark](https://github.com/LF3551/data-cleaning-benchmark). The benchmark ran with Python 3.9, DuckDB 1.4.5, Polars 1.36.1, and pandas 2.3.3. Each engine ran in a fresh process measured via `/usr/bin/time -l` (`real` wall time and `maximum resident set size`), taking the median of runs 2–4 after a warm-up run.

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

```sql title="clean_orders.sql" {3-10,27}
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:

```python title="clean_orders_polars.py" {5-14,22-23}
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()
)
```

> [!TIP]
> To add a **quarantine table** in either DuckDB or Polars, assign a `failure_reason` expression (`CASE WHEN amount <= 0 THEN 'non_positive_amount' ...`) *before* filtering, then write `failure_reason IS NULL` to your clean Parquet output and `failure_reason IS NOT NULL` to `quarantine.parquet`.

## 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](https://www.alekseialeinikov.com/en/blog/topics/data/data-governance-gcp-2026).

## 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](https://www.alekseialeinikov.com/en/blog/topics/data/duckdb-explained-vs-sqlite-polars-bigquery)
