Data Pipelines for AI

Updated · 9 min read
mediumPython 3.13aidata-engineeringpipelinespandasparquetsql

A data pipeline is the series of steps that turns raw data from many sources into clean, consistent data an AI system can use. It ingests data from files, databases, APIs and logs; validates it against rules; cleans and transforms it; and stores it in a reliable format, recording what happened along the way. Most AI failures that look like model problems are really data problems, so a careful pipeline is often worth more than a better model.

The Stages

StageDescription
IngestionIt is used to collect data from files, databases, APIs, events and application logs
ValidationCheck types, required fields, allowed values and references; quarantine what fails
Cleaning and transformationIt is used to deduplicate, standardize formats and fix or drop invalid values
StorageWrite typed, columnar files (Parquet) or tables in a warehouse
Lineage and reportsIt is used to record where each output came from and what changed
OrchestrationRun steps in order on a schedule, with retries and alerts; tools include Airflow and Dagster

ETL transforms data before loading it into storage; ELT loads raw data first and transforms it inside the warehouse with SQL. Batch pipelines run on a schedule (every night); streaming pipelines process each event as it arrives.

Example: Messy Raw Data

Raw in, checked and recorded, clean out: the same every run

This program makes two made-up exports from school systems, with the problems real exports have. The programs in this lesson need pip install pandas pyarrow.

Python
import csv
import random
 
# Made-up raw exports from two school systems, with the problems real exports have
rng = random.Random(16)
grades = [9, 10, 11, 12]
students = []
for i in range(1, 41):
    students.append({"student_id": f"S{i:03}", "grade": rng.choice(grades),
                     "enrolled": rng.choice(["2026-08-18", "08/18/2026", "2026-08-19", "Aug 18 2026"])})
students.append(dict(students[4]))                       # a duplicate record
students[7]["grade"] = 14                               # an impossible grade
with open("raw_students.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=students[0].keys())
    w.writeheader()
    w.writerows(students)
 
fees = []
for s in students[:40]:
    fees.append({"student_id": s["student_id"], "fee": rng.choice(["lab", "library", "sports", "tuition"]),
                 "amount": rng.choice(["45", "15", "60", "250", "", "two hundred"])})
fees.append({"student_id": "S999", "fee": "lab", "amount": "45"})   # a student who doesn't exist
with open("raw_fees.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=fees[0].keys())
    w.writeheader()
    w.writerows(fees)
print("Wrote raw_students.csv:", len(students), "rows; raw_fees.csv:", len(fees), "rows")
Output
Wrote raw_students.csv: 41 rows; raw_fees.csv: 41 rows

Explanation: raw_students.csv has a duplicate record, an impossible grade (14) and enrollment dates in four different formats. raw_fees.csv has empty and non-numeric amounts ("two hundred") and a fee for a student who doesn't exist (S999). Each of these would quietly damage a model or a report.

Example: A Validating, Reproducible Pipeline

Python
import hashlib
import json
 
import pandas as pd
 
def fingerprint(path):
    return hashlib.sha256(open(path, "rb").read()).hexdigest()[:12]
 
def run_pipeline():
    report = {"input": {"raw_students.csv": fingerprint("raw_students.csv"), "raw_fees.csv": fingerprint("raw_fees.csv")}}
    students = pd.read_csv("raw_students.csv", dtype=str)
    fees = pd.read_csv("raw_fees.csv", dtype=str, keep_default_na=False)
 
    # 1. Deduplicate
    before = len(students)
    students = students.drop_duplicates()
    report["duplicate students removed"] = before - len(students)
    # 2. Standardize dates: every format becomes YYYY-MM-DD
    students["enrolled"] = students["enrolled"].apply(lambda d: pd.to_datetime(d, format="mixed").strftime("%Y-%m-%d"))
    # 3. Validate values against the rules; quarantine what fails instead of silently dropping it
    students["grade"] = students["grade"].astype(int)
    bad_grade = ~students["grade"].between(9, 12)
    report["invalid grades quarantined"] = students.loc[bad_grade, "student_id"].tolist()
    students = students[~bad_grade]
    fees["amount"] = pd.to_numeric(fees["amount"], errors="coerce")       # "" and "two hundred" become missing
    report["missing or invalid fee amounts"] = int(fees["amount"].isna().sum())
    unknown = ~fees["student_id"].isin(students["student_id"])
    report["fees for unknown students"] = fees.loc[unknown, "student_id"].tolist()
    fees = fees[~unknown & fees["amount"].notna()]
    # 4. Write clean, typed, columnar output
    students.sort_values("student_id").to_parquet("students.parquet", index=False)
    fees.sort_values(["student_id", "fee"]).to_parquet("fees.parquet", index=False)
    report["output"] = {"students.parquet": len(students), "fees.parquet": len(fees)}
    return report
 
report = run_pipeline()
print(json.dumps(report, indent=1))
json.dump(report, open("quality_report.json", "w"), indent=1)          # lineage: what went in, what came out
 
first = (fingerprint("students.parquet"), fingerprint("fees.parquet"))
run_pipeline()                                                          # run it again on the same input
print("Second run gives identical output (idempotent):", first == (fingerprint("students.parquet"), fingerprint("fees.parquet")))
print(pd.read_parquet("students.parquet").dtypes.to_dict())
Output
{
 "input": {
  "raw_students.csv": "8e8cfaf131e1",
  "raw_fees.csv": "1c0d00bf93e6"
 },
 "duplicate students removed": 1,
 "invalid grades quarantined": [
  "S008"
 ],
 "missing or invalid fee amounts": 8,
 "fees for unknown students": [
  "S008",
  "S999"
 ],
 "output": {
  "students.parquet": 39,
  "fees.parquet": 31
 }
}
Second run gives identical output (idempotent): True
{'student_id': <StringDtype(na_value=nan)>, 'grade': dtype('int64'), 'enrolled': <StringDtype(na_value=nan)>}

Explanation:

  • Deduplicate removes the 1 copied student. pd.to_datetime(format="mixed") turns all four date styles into one: 2026-08-18.
  • Validate and quarantine: student S008's grade of 14 fails the rule (9 to 12), so S008 is set aside and listed in the report, not silently deleted. pd.to_numeric(errors="coerce") turns "" and "two hundred" into missing values: 8 amounts are missing or invalid. Fees for S008 and S999 point to no valid student.
  • Parquet stores the result as typed columns (grade is an integer, not text), compressed and fast to read, the usual format for analytics and ML.
  • The quality report records the input fingerprints, every problem and the output counts: that is lineage. Months later you can tell exactly which data a model was trained on.
  • Idempotent: running the pipeline again on the same input gives byte-for-byte the same output. That makes reruns and backfills safe.

Example: Preparing Data with SQL

SQL is the language of data warehouses. This program loads the clean Parquet files into SQLite and runs three common kinds of query.

Python
import sqlite3
 
import pandas as pd
 
db = sqlite3.connect(":memory:")                     # SQL on the clean data from the pipeline
pd.read_parquet("students.parquet").to_sql("students", db, index=False)
pd.read_parquet("fees.parquet").to_sql("fees", db, index=False)
 
print("1. Join and aggregate: fees owed per grade")
for row in db.execute("""
    SELECT s.grade, COUNT(*) AS fees, SUM(f.amount) AS total
    FROM fees f JOIN students s ON s.student_id = f.student_id
    GROUP BY s.grade ORDER BY s.grade"""):
    print("  ", row)
 
print("\n2. Students with no fee record at all (a LEFT JOIN finds what's missing)")
missing = db.execute("""
    SELECT s.student_id FROM students s LEFT JOIN fees f ON f.student_id = s.student_id
    WHERE f.student_id IS NULL ORDER BY s.student_id""").fetchall()
print("  ", [m[0] for m in missing])
 
print("\n3. A window function: each student's fee and the running total within their grade")
for row in db.execute("""
    SELECT s.grade, f.student_id, f.amount,
           SUM(f.amount) OVER (PARTITION BY s.grade ORDER BY f.student_id) AS running_total
    FROM fees f JOIN students s ON s.student_id = f.student_id
    WHERE s.grade = 9 ORDER BY f.student_id LIMIT 4"""):
    print("  ", row)
Output
1. Join and aggregate: fees owed per grade
   (9, 7, 930.0)
   (10, 4, 605.0)
   (11, 8, 930.0)
   (12, 12, 785.0)
 
2. Students with no fee record at all (a LEFT JOIN finds what's missing)
   ['S004', 'S006', 'S009', 'S013', 'S018', 'S021', 'S038', 'S040']
 
3. A window function: each student's fee and the running total within their grade
   (9, 'S007', 15.0, 15.0)
   (9, 'S010', 60.0, 75.0)
   (9, 'S017', 250.0, 325.0)
   (9, 'S020', 45.0, 370.0)

Explanation:

  • A join with GROUP BY totals fees per grade: grade 9 has 7 fees totaling $930.
  • A LEFT JOIN with IS NULL finds what's missing: 8 students have no fee record at all, worth checking before a model learns that "no record" means "paid".
  • A window function (SUM(...) OVER (PARTITION BY ... ORDER BY ...)) adds a running total within each grade without collapsing rows, the kind of feature models often need.

Where Data Lives

StoreDescription
Object storage and data lakesCheap storage for raw files of any kind (CSV, JSON, Parquet, images)
Data warehouseIt is used to query clean, structured tables with SQL at scale
LakehouseWarehouse-style tables and SQL on top of files in a lake
Feature storeIt is used to serve the same computed features for training (offline) and live predictions (online), so they match

Common Mistakes

Cleaning by hand in a notebook. It can't be repeated or checked; write the steps as a pipeline.

Silently dropping bad rows. Quarantine and report them, so someone fixes the source.

Mixing formats. One date format, one unit, one ID style throughout.

No record of the data version. Without lineage, a model's results can't be reproduced.

Interview Corner

What makes a good data pipeline for AI?

It validates inputs against explicit rules, quarantines and reports failures, transforms data reproducibly and idempotently, stores typed outputs, and records lineage: what went in, what came out and what changed. It runs automatically, with alerts when checks fail.

What is the difference between ETL and ELT?

ETL transforms data before loading it into the target store; ELT loads raw data first and transforms it inside the warehouse, usually with SQL. ELT is common with modern cloud warehouses.

Practice

Exercise: a new rule. Add a validation rule that fee amounts must be one of 15, 45, 60 or 250, and report any others. Do any rows fail? Then add a raw fee row with an amount of 450 and run the pipeline again.

Check your understanding:

  1. Why is S008 quarantined instead of deleted?
  2. What does "idempotent" mean for a pipeline, and why does it matter?
  3. What did the LEFT JOIN find, and why does it matter for a model?

Quick check: data pipelines

4 questions
1How many duplicate student records did the pipeline remove?
2What does the quality report record?
3Why store the result as Parquet?
4What does a feature store solve?

Key Takeaways

Quick reference

NeedCode
Remove duplicatesdf.drop_duplicates()
Mixed date formatspd.to_datetime(d, format="mixed")
Bad numbers to missingpd.to_numeric(col, errors="coerce")
Write and read Parquetdf.to_parquet(path), pd.read_parquet(path)
Find missing matchesLEFT JOIN ... WHERE right.key IS NULL
Running totalSUM(x) OVER (PARTITION BY g ORDER BY k)

Was this tutorial helpful?

Lesson 82 of 186