Aller au contenu

Leçon 19 · Validation and Pipelines

Building a Repeatable Cleaning Pipeline

Turn cleaning code into a repeatable pipeline with small pure functions, configuration, step reports, idempotent output and safe handling of rejected rows.

A notebook full of experiments is a fine place to explore. It is a risky place to produce a number that others depend on. A pipeline runs the same steps, in the same order, from raw input to clean output with one command.

The shape

flowchart LR
  A["Raw input"] --> B["Parse"]
  B --> C["Standardize"]
  C --> D["Validate"]
  D --> E["Clean output"]
  D --> F["Quarantine"]
  E --> G["Run report"]
  F --> G

Every input row ends up in the output, in quarantine or in a counted removal.

Design principles

  1. Pure steps. Each function takes data and returns new data, without hidden changes.
  2. One job per step. Small steps are easier to test and change.
  3. Rules as configuration. Mappings and limits live in one place.
  4. Deterministic output. The same input and rules give the same result. Pass dates in as values instead of reading the clock inside a step.
  5. Accounting. Every row is accounted for.

A complete small pipeline

Python A pipeline with accounting

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The accounting assert fails loudly if a code change ever drops rows silently. In production code, raise a clear exception instead, because Python can run with assertions disabled.

This example treats rows with the same ID as duplicates. In real use, compare the other fields too and quarantine conflicts. It also reports only the first problem per row, to stay short. (float accepts text such as nan and inf, so a real rule should reject those as well.)

Idempotence

For many cleaning steps, running a step on its own output should not change anything. That catches rules that stack, such as adding a prefix each time.

Python Check that a step is idempotent

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

pandas pipelines

In pandas, you can write each step as a function from DataFrame to DataFrame and chain them with .pipe.

Python pandas: chain steps with pipe

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

assign returns a new DataFrame, so the raw one is unchanged.

Make runs traceable

Each run should record:

  • The input file name and a checksum (a fingerprint of the content).
  • The version of the code and the mapping files.
  • Row counts at each stage and rejection reasons.
  • The run time and outcome.

Then you can answer "which rules produced this report?".

Write output safely

Write to a temporary file or staging table, validate it, then rename or swap it into place. That way a crash is much less likely to damage the previous good output. Make reruns replace results rather than append to them.

Where it runs

A scheduled script may be enough. As the number of steps and dependencies grows, teams often use workflow orchestrators. Data engineering covers that area. Keep secrets such as database passwords out of the code and the repository.

Common mistake: editing the cleaned file by hand after the pipeline runs. The next run erases the edit. Put the correction into a rule or a reviewed corrections table.

Configuration you can review

Mappings, limits, accepted formats and the list of required columns change more often than code logic. Keep them in small, readable files under version control, and load them at the start of the run. Validate the configuration too: a duplicate mapping key or a minimum above its maximum should stop the run before any data is processed.

Do not hide different behavior behind switches that nobody remembers. If one source needs special handling, name that rule after the source and explain it.

Handling surprises

Decide which problems are about one row and which are about the run. A bad amount in one row can go to quarantine. A missing column, an unreadable file or a missing mapping file should stop everything. Avoid a broad except Exception: pass around a step. It hides programming errors as if they were data errors, and rows disappear without explanation. Catch the specific exceptions you expect.

Growing the design

Start with plain functions and a list that shows their order. Order matters: parsing must come before range checks, and standardizing must come before matching duplicates. When a step depends on an earlier one, say so in its description.

If data no longer fits in memory, you can process it in chunks. Take care with steps that need to see everything at once, such as duplicate detection and group medians. Those may need a database or a first pass that collects what they need.

Rebuild from scratch

From time to time, delete the working outputs in a test location and rebuild everything from raw files. If the results differ and no rule changed, something depends on hidden state, such as a manual edit, a file outside version control or the current date.

Who runs it?

Write down how to start a run, where the inputs come from and what to do after a failure. A pipeline that only its author can operate is still a manual process. State whether it is safe to run again after a partial failure, and test that claim.

Also decide who reads the run report. Rejected rows need an owner who repairs them or explains them. Without that person, the quarantine file only grows.

Small releases

Change one rule at a time when you can. Run the old and new versions on the same input and compare the counts. If something unexpected moves, you know which change caused it, and you can return to the previous version while you investigate.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does it mean for every row to be accounted for?

    Accounting shows that nothing disappeared without a record.
  2. 2. How can you test that a cleaning step is idempotent?

    An idempotent step leaves already processed data unchanged. Test with varied inputs.
  3. 3. Why write output to a staging location first?

    You swap in the new result only after it passes checks.

Summary

  • Build pipelines from small, pure, testable steps.
  • Keep rules as configuration and make output deterministic.
  • Account for every row and check idempotence.
  • Record versions and write outputs safely.

Next: Testing and Documenting Cleaning Work

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.