Clean and validate
Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:30 on Wednesday. A new supplier sends a six-line test file before the real feed begins: 50 million order lines a day. Your loader crashes on the fourth row, at a quantity of two. Your quick fix, a try/except that skips whatever fails, loads the file without a word: four rows, one with a quantity of -3 and one for a product that does not exist. Nora reads the log: "Two rows are gone and nobody knows which. Every row needs an ending that you chose."
You'll learn to
- Parse text into real types: money as `Decimal`, times in UTC
- Send bad rows to a quarantine with a reason, and count them
- Check that rows read = rows loaded + rows rejected
- Make validation fast: cast in bulk, explain only the rejects
Learn
Three endings for every row
Both versions of the loader made the same mistake: they let Python decide what happens to a bad row. The first let it crash. The second let it shrug.
A pipeline has to decide on purpose, and there are only three endings.
- Clean: the row is valid. Load it.
- Fix: the row is valid after a safe change that everyone agreed on: trim spaces, strip a
$, turn""intoNone. - Reject: the row breaks a rule. Do not load it, and do not drop it silently. Put it in a quarantine file with the reason, and count it.
The good rows load, someone fixes the source, and one line of arithmetic proves that nothing went missing: rows read = rows loaded + rows rejected.
Every row ends in one of two places
A row read as text is judged clean, fixable or rejected; clean and fixed rows are loaded, rejected rows go to a quarantine with their reason, and both are counted.
Read it left to right. Every row ends in one of the two boxes on the right, and the two counts must add up to the rows read. There is no arrow called "skipped".
Parse on purpose: money is not a float
Everything from a CSV is text, so cleaning starts with parsing: turning text into a real type. Write one small function per type. Each one either returns a clean value or raises ValueError with a message a person can act on.
Prices need extra care. A Python float stores numbers as binary fractions, and most decimal amounts have no exact binary form. Add up a million prices and the total drifts by cents that finance will find.
For money, use Decimal. Decimal("0.10") + Decimal("0.20") is exactly Decimal("0.30"). Build it from the text, never from a float. Postgres NUMERIC, Spark DecimalType and warehouse NUMBER(10,2) columns exist for the same reason.
Parse a price
from decimal import Decimal, InvalidOperation
def parse_price(raw):
s = (raw or "").strip().replace("$", "")
if s == "":
return None
if "," in s and "." not in s:
s = s.replace(",", ".") # 14,99 written the European way
try:
value = Decimal(s)
except InvalidOperation:
raise ValueError(f"not a price: {raw!r}")
if value < 0:
raise ValueError(f"negative price: {raw!r}")
return value.quantize(Decimal("0.01"))
for raw in ["$12.00", " 12.5 ", "14,99", "", "free", "-4.00"]:
try:
print(repr(raw), "->", parse_price(raw))
except ValueError as e:
print(repr(raw), "-> rejected:", e)
print(0.1 + 0.2, Decimal("0.1") + Decimal("0.2"))
Six inputs, three endings. $12.00, 12.5 and 14,99 are fixed and come out with two decimals (quantize(Decimal("0.01")) does that). The blank becomes None, not 0: "unknown" and "free" are different facts. free and -4.00 are rejected with a reason. The last line is the float problem in one sum.
Dates: parse, then move everything to UTC
Timestamps arrive in many shapes. SwiftKart's own export writes 2025-06-01 12:46:56. The landing files write 2025-06-01T12:46:56Z. The supplier writes 01/06/2025. Is that 1 June or 6 January? No code can tell. Only the source can: ask, and write the answer down.
In Python, datetime.fromisoformat reads the standard ISO 8601 form, including the Z that means UTC. datetime.strptime(s, "%d/%m/%Y") reads a format that you name. Try the formats you agreed on, and reject anything else.
Then normalise: convert every timestamp to UTC and write it in one format. Comparing timestamps as text in mixed formats is how "keep the latest row" quietly picks the wrong one.
Five strings in, one format out
Three differently written timestamps all become 2025-06-01 12:46:56 in UTC, the supplier date 01/06/2025 becomes midnight on 1 June because the supplier confirmed day first, and the text June 1st is rejected.
The left column is what sources send, the right column is what your tables store. The first three arrows end in the same box: three ways to write one moment.
Several formats, one result
from datetime import datetime, timezone
def parse_ts(raw):
s = raw.strip()
try:
dt = datetime.fromisoformat(s)
except ValueError:
try:
dt = datetime.strptime(s, "%d/%m/%Y") # the supplier confirmed: day first
except ValueError:
raise ValueError(f"unknown date format: {raw!r}")
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc) # agreed: times without a zone are UTC
return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
for raw in ["2025-06-01T12:46:56Z", "2025-06-01 12:46:56", "2025-06-01T14:46:56+02:00", "01/06/2025", "June 1st"]:
try:
print(f"{raw:27} -> {parse_ts(raw)}")
except ValueError as e:
print(f"{raw:27} -> rejected: {e}")
The output matches the picture line by line. Two calls do different jobs here. astimezone(timezone.utc) converts a time that carries an offset. replace(tzinfo=...) only labels a time that had no zone. Mix them up and data shifts by hours.
Check the whole row, keep the reasons
Parsing checks one value. Validation checks the whole row against the rules its readers rely on: required fields are there, quantities are above zero, product ids exist.
Write a function that returns a list of problems, empty when the row is fine. Reporting every problem at once saves the supplier a round trip.
Then split the stream. Good rows go on. Bad rows go to the quarantine list with their reasons. Finish by reconciling, read = good + rejected, and fail the whole run if too many rows are rejected, say over 5%. A supplier who suddenly sends 40% garbage needs a person, not a quiet partial load.
Validate the supplier's six lines
import csv
with open("data/products.csv", newline="") as f:
product_ids = {int(p["product_id"]) for p in csv.DictReader(f)}
def problems(row):
errs = []
if not row["order_id"].isdigit():
errs.append("order_id is not a number")
try:
if int(row["qty"]) <= 0:
errs.append("qty must be above 0")
except ValueError:
errs.append(f"qty is not a number: {row['qty']!r}")
if not row["product_id"].isdigit() or int(row["product_id"]) not in product_ids:
errs.append(f"unknown product {row['product_id']}")
return errs
good, rejected = [], []
with open("feeds/order_lines.csv", newline="") as f:
for row in csv.DictReader(f):
errs = problems(row)
if errs:
rejected.append({**row, "reasons": "; ".join(errs)})
else:
good.append(row)
print(f"read {len(good) + len(rejected)} = good {len(good)} + rejected {len(rejected)}")
for r in rejected:
print(r["order_id"], r["line_no"], "->", r["reasons"])
Read 6 = good 2 + rejected 4, and each rejected row carries a reason someone can act on. In a real job, rejected is written to a quarantine file or table next to the load, with the run date.
The feed after validation
| orderid | lineno | productid | qty | outcome |
|---|---|---|---|---|
| 1081 | 1 | 101 | 1 | good |
| 1081 | 2 | 999 | 1 | rejected: unknown product 999 |
| 1082 | 1 | 103 | -3 | rejected: qty must be above 0 |
| 1082 | 2 | 110 | two | rejected: qty is not a number |
| 1083 | 1 | 112 | 2 | good |
| x1084 | 1 | 104 | 1 | rejected: orderid is not a number |
Six rows read, two loaded, four quarantined with reasons: 6 = 2 + 4. Nothing crashed and nothing vanished.
The same rules with pydantic
Runs on your laptop:
from decimal import Decimal
from pydantic import BaseModel, Field, ValidationError
class OrderLine(BaseModel):
order_id: int
line_no: int
product_id: int
qty: int = Field(gt=0)
unit_price: Decimal
try:
OrderLine(order_id="1082", line_no="1", product_id="103", qty="-3", unit_price="9.99")
except ValidationError as e:
print(e.error_count(), e.errors()[0]["loc"], e.errors()[0]["msg"])
1 ('qty',) Input should be greater than 0
pydantic is the most used validation library in Python. You describe a row as a class, and it checks every row against it: it turns "1082" into 1082 and rejects -3 with a clear message. It is not available in this browser, so this card shows its output on a laptop. Module 7 builds data contracts on the same idea.
Silent coercion loses data. errors="coerce", a try/except: pass or a default of 0 all turn a broken value into one that looks valid: a blank price becomes 0 and revenue drops. Count every coercion, keep a reason for every reject, and never use float for money.
The validator is the slowest step
The six lines work. Then the real feed starts, and your validator takes longer than the rest of the pipeline put together.
Speed comes down to one question: where does the work for each value run? A rule on a typed column, such as qty > 0 over a column of integers, is one tight loop in C. The same rule on text runs in Python, once per value, and that is 30 to 100 times slower.
The most expensive step is usually turning text into types, and dates are the worst. datetime.strptime is flexible and slow. datetime.fromisoformat accepts one format and is about 40 times faster.
So parse once, into typed columns, with the fastest parser your agreed format allows. Every rule after that is nearly free.
300,000 order lines: milliseconds per step, in this browser
Bars compare the time of each validation step on 300,000 rows: strptime is slowest at 1,537 ms, csv.DictReader 384, a Python rule loop 126, DuckDB TRY_CAST rules 108, to_numeric on text 104, to_datetime with a format 49, fromisoformat 40, and an int64 comparison under 1 ms.
The longest bar comes first. These are medians of three runs on 300,000 rows in Pyodide 0.26.4 (WebAssembly, one thread), so a server is faster and DuckDB there uses every core. Do not quote the milliseconds. Quote the ratios: about 40 times between the two date parsers, and 30 to 100 times between a rule on text and the same rule on a typed column.
pandas: short, fast, and quiet about losses
pandas loads a table into memory and runs each operation on a whole column at once. For data that fits in memory, a cleaning step is often one line where plain Python takes ten: pd.to_numeric(df.qty, errors="coerce"), pd.to_datetime, drop_duplicates, groupby, merge.
Use it for analysis, notebooks and small batch jobs. Prefer plain Python when you need a reason for each reject, when data must stream, or for a small function with no dependencies. Use DuckDB or Spark when the data does not fit in memory. And in an interview, use pandas only when it is allowed: a "no pandas" question is testing dicts and loops.
Now run the same checks in pandas, and count what comes out.
The same checks in pandas
import pandas as pd
df = pd.read_csv("feeds/order_lines.csv", dtype=str)
qty = pd.to_numeric(df["qty"], errors="coerce")
order_ok = df["order_id"].str.isdigit()
bad = df[qty.isna() | (qty <= 0) | ~order_ok]
print(len(df), "rows,", len(bad), "bad")
print(bad[["order_id", "line_no", "qty"]].to_string(index=False))
print("values turned into NaN by coerce:", int(qty.isna().sum()))
Six rows, 3 bad. But the plain-Python validator found 4. The unknown product 999 slipped through because no rule here checked it, and no row has a reason. Look at the last line too: errors="coerce" turned one value into NaN without a word. Count the NaNs you create.
A fast path, and a slow path for rejects
You want the speed of bulk checks and the reasons of plain Python. So split validation in two.
The fast path casts and checks every row in bulk, inside an engine. In DuckDB, TRY_CAST returns NULL where a cast fails, so one query can flag every quantity that is not a number. read_csv(..., store_rejects = true) goes further: it records each row that does not fit the declared types in a table called reject_errors, with its line number.
The slow path runs your detailed Python rules, but only on the rows the fast path flagged. That is usually a fraction of a percent, so its cost hardly matters, and every reject still gets a reason.
Then the same gate as before: read = loaded + rejected, and a limit on the reject rate.
Six rows through the fast path and the slow path
The six-row supplier file goes through five steps: read as text, cast in bulk which flags two rows, rules on typed columns which flag two more, Python reasons for the four flagged rows only, and a reconciliation of 6 read against 2 loaded plus 4 rejected.
Read everything as text. All six rows come in with every column as text (
all_varchar = truein DuckDB,dtype=strin pandas). Nothing is lost or guessed yet.Cast in bulk. One pass tries to turn every
qtyandorder_idinto an integer.twoandx1084cannot be cast and becomeNULL. Two rows are flagged.Rules on typed columns. Now each rule is a plain comparison on numbers.
-3is not above 0, and 999 is not a known product. Four rows are flagged in all, and two are good.Explain only the flagged rows. The slow Python rules run on 4 rows, not 6, and give each one a reason. On the real feed that is a fraction of a percent of 50 million.
Reconcile and gate. Read 6 = loaded 2 + rejected 4. Four out of six is far above a 5% limit, so this run fails on purpose and someone calls the supplier.
Read it top to bottom. The green steps touch every row and run inside an engine. Only the amber step runs your Python, and only on what the green steps flagged.
The fast path in DuckDB
import duckdb
duckdb.sql("""
CREATE TABLE lines AS
SELECT * FROM read_csv('feeds/order_lines.csv', header = true,
columns = {'order_id': 'INTEGER', 'line_no': 'INTEGER', 'product_id': 'INTEGER',
'qty': 'INTEGER', 'unit_price': 'DECIMAL(10,2)'},
store_rejects = true)
""")
print(duckdb.sql("SELECT count(*) FROM lines").fetchone()[0], "rows fit the types")
print(duckdb.sql("SELECT line, column_name, error_type FROM reject_errors ORDER BY line").fetchall())
raw = duckdb.sql("SELECT * FROM read_csv('feeds/order_lines.csv', all_varchar = true)")
print(duckdb.sql("""
SELECT order_id, line_no, qty, product_id
FROM raw
WHERE TRY_CAST(order_id AS INTEGER) IS NULL
OR COALESCE(TRY_CAST(qty AS INTEGER), 0) <= 0
OR COALESCE(TRY_CAST(product_id AS INTEGER), 0) NOT BETWEEN 101 AND 120
ORDER BY order_id, line_no
""").fetchall())
First query: store_rejects caught the two rows whose text cannot become the declared type (file lines 5 and 7, counting the header as line 1). But -3 and product 999 are valid integers, so business rules still need their own checks. Second query: all four bad rows in one pass. Only those four would go on to the Python slow path.
Remember: read = loaded + rejected. Every row ends in one of the two, and every reject has a reason.
Numbers to remember
| Step, on 300,000 values | Time in this browser | Good to know |
|---|---|---|
| datetime.strptime | 1.5 s | about 3 µs per value on a laptop with native CPython 3.12 |
| datetime.fromisoformat | 40 ms | about 40 times faster; reads ISO 8601 only |
| A plain Python loop with three cheap rules | 126 ms | the rules run once per value |
| pd.tonumeric and .str methods on a text column | 104 ms and 26 ms | Python-level loops too (Lesson 3.7 explains why) |
| qty 0 on an int64 column | under 1 ms | one loop in C |
Scaled up: two timestamp columns on 50 million rows cost about 300 s a day with strptime and about 9 s with fromisoformat, on one core. pydantic v2 validates in Rust, and TypeAdapter(list[OrderLine]) checks a whole list in one call. Real pipelines validate right after ingestion: pydantic models in Python services, Great Expectations or Soda checks on tables, dbt tests and contracts in the warehouse, Databricks expectations that flag failing rows, drop them or stop the pipeline. All of them do what you did here: rules as code, bad rows routed with a reason, counts reported.
What changed at SwiftKart
The supplier's test file ends the day as a short report: 6 rows read, 2 loaded, 4 in quarantine, each with its reason. The supplier fixes the export before the real feed starts, and confirms in writing that their dates are day first.
For the 50 million lines a day, the loader casts and checks in bulk in DuckDB, sends only flagged rows to the Python rules, and fails the run above 5% rejects. Prices are Decimal, times are UTC, and Tess's totals match the supplier's invoice to the cent.
One question is left over. Why is a typed column so much faster, and smaller, than the same values as Python objects? The last lesson of this module opens up memory itself.
In one line
Give every row one of three endings (clean, fix, or reject with a reason), keep money as Decimal and times in UTC, check that read = loaded + rejected, and validate in bulk before you explain the rejects.
Interview corner
Your validation step takes longer than the rest of the pipeline. How do you find and fix the cost?
I measure the per-value cost of each step and multiply by the row count. Usually the time is in turning text into types once per value in Python: datetime.strptime costs about 3 µs per value natively, so two timestamp columns on 50 million rows is 300 s a day, while fromisoformat is about 0.1 µs. Then I move the checks to typed columns: a NumPy comparison runs in nanoseconds per value, whereas pandas .str methods and to_numeric on object columns are still Python loops. The design is a fast path in bulk (DuckDB TRY_CAST, store_rejects, or vectorised masks) and a slow Python path that explains only the flagged rows.
How do you handle bad records in a pipeline?
I validate right after ingestion with rules written as code. Rows that fail go to a quarantine table or file with the reasons and the run id, and the good rows load. I reconcile the counts (read = loaded + rejected) and alert or fail the run when the reject rate crosses a threshold, because a sudden spike usually means the source changed.
Why not use float for money?
Floats are binary fractions, so most decimal amounts such as 0.1 cannot be stored exactly; sums drift and equality checks fail. Decimal in Python, NUMERIC in Postgres or DECIMAL(p, s) in Spark and warehouses store exact decimal values. I build Decimals from strings, never from floats, and round with an explicit rule.
When would you use pandas, and when not?
pandas is great for data that fits in memory: exploration, notebooks, cleaning and small batch jobs, where whole-column operations are short and fast. I avoid it when the data is bigger than memory (DuckDB or Spark instead), when I need streaming or a reason for every rejected row, or when an interview explicitly asks for plain Python.