TExcelTAD
Home › Data for ML: Types, Formats, Sources & Quality › A Reproducible Data Quality Report

A Reproducible Data Quality Report

The lessons of this section each found one kind of problem. In a real project, the findings have to reach other people: the data owner who can fix the source, the team that will train the model, a reviewer who must sign off, and you, three months later, wondering why the model changed. A data quality report collects the checks in one document. It is reproducible when anyone can regenerate exactly the same report from the same data version, which means it is produced by code, never by hand.

What a good report contains

Part Content
identity dataset name and version (fingerprint), source, date of the data, version of the checking code
overview rows, columns, grain (what one row is), key, label
schema each column's expected and actual type
findings each check with a severity, the number of affected rows and examples
distributions class counts, key statistics, and figures
decision can the data be used as is, after fixes, or not at all?

The severity turns a list of numbers into a decision. A common scheme: error (the data must not be used until fixed: duplicated keys, labels outside the allowed set), warning (needs a decision: 5% missing incomes, a unit mix-up in some rows), info (worth knowing: a skewed column).

Checks as data

The trick that makes a report reproducible and easy to extend is to describe the expectations as data, a configuration, and to write the checks as small functions that read it. The checks never change when the dataset changes; only the configuration does.

python · try it yourself
import numpy as np
import pandas as pd

def make_loans():
    rng = np.random.default_rng(42)
    n = 200
    df = pd.DataFrame({
        "loan_id": [f"L{i:04}" for i in range(n)],
        "age": rng.integers(19, 75, n),
        "income": np.round(rng.lognormal(10.7, 0.45, n), -2),
        "country": rng.choice(["VN", "DE", "IN"], n, p=[0.5, 0.3, 0.2]),
        "default": (rng.random(n) < 0.12).astype(int),
    })
    df.loc[[5, 17, 88], "age"] = [-1, 230, -1]               # placeholders and a typo
    df.loc[rng.choice(n, 14, replace=False), "income"] = np.nan
    df.loc[[30, 31], "country"] = ["vn", "Vietnam"]
    df.loc[150, "default"] = 2                                # an impossible label
    return pd.concat([df, df.iloc[[10, 11]]], ignore_index=True)   # two duplicated rows

CONFIG = {
    "key": "loan_id",
    "label": "default",
    "types": {"loan_id": "object", "age": "int", "income": "float", "country": "object", "default": "int"},
    "ranges": {"age": (18, 100), "income": (0, 5_000_000)},
    "allowed": {"country": {"VN", "DE", "IN"}, "default": {0, 1}},
    "max_missing_share": 0.05,
}

def check_key(df, cfg):
    dup = df[cfg["key"]].duplicated(keep=False)
    return "error", int(dup.sum()), df.loc[dup, cfg["key"]].unique()[:3].tolist()

def check_types(df, cfg):
    tests = {"int": pd.api.types.is_integer_dtype, "float": pd.api.types.is_float_dtype,
             "object": pd.api.types.is_object_dtype}
    bad = [f"{c}: {df[c].dtype}" for c, t in cfg["types"].items() if not tests[t](df[c])]
    return "error", len(bad), bad                             # counts columns, not rows

def check_missing(df, cfg):
    share = df.isna().mean()
    over = share[share > cfg["max_missing_share"]]
    return "warning", int(df.isna().any(axis=1).sum()), [f"{c}: {s:.1%}" for c, s in over.items()]

def check_ranges(df, cfg):
    hits = {c: df[(df[c] < lo) | (df[c] > hi)][c].tolist() for c, (lo, hi) in cfg["ranges"].items()}
    return "warning", sum(len(v) for v in hits.values()), [f"{c}: {v}" for c, v in hits.items() if v]

def check_allowed(df, cfg):
    bad = {c: sorted(map(str, set(df[c].dropna()) - ok)) for c, ok in cfg["allowed"].items()}
    sev = "error" if bad.get(cfg["label"]) else "warning"
    rows = sum(int((~df[c].isin(ok)).sum()) for c, ok in cfg["allowed"].items())
    return sev, rows, [f"{c}: {v}" for c, v in bad.items() if v]

CHECKS = [("unique key", check_key), ("column types", check_types), ("missing values", check_missing),
          ("value ranges", check_ranges), ("allowed values", check_allowed)]

df = make_loans()
for name, fn in CHECKS:
    severity, rows, examples = fn(df, CONFIG)
    status = "ok" if rows == 0 else severity
    print(f"{name:15} {status:8} rows={rows:3}  {examples}")
unique key      error    rows=  4  ['L0010', 'L0011']
column types    ok       rows=  0  []
missing values  warning  rows= 14  ['income: 6.9%']
value ranges    warning  rows=  3  ['age: [-1, 230, -1]']
allowed values  error    rows=  3  ["country: ['Vietnam', 'vn']", "default: ['2']"]

Each check returns the same three things: a severity, the number of affected rows, and a few examples. That uniform shape is what lets the report assemble itself.

Writing the report

The report itself is generated text, here Markdown, which renders nicely in code review tools, wikis and notebooks, with a machine-readable JSON summary next to it so that later runs can be compared automatically. Everything that identifies the run goes at the top: the dataset fingerprint (as in Dataset Versioning), the date the data refers to, and the version of the checking code. Note what is not in it: the current time. A report that prints "generated at 14:03:22" changes every time it is run, and two runs on the same data can no longer be compared byte for byte; pass dates in explicitly instead.

python · try it yourself
import hashlib
import json
import numpy as np
import pandas as pd

def make_loans():
    rng = np.random.default_rng(42)
    n = 200
    df = pd.DataFrame({
        "loan_id": [f"L{i:04}" for i in range(n)],
        "age": rng.integers(19, 75, n),
        "income": np.round(rng.lognormal(10.7, 0.45, n), -2),
        "country": rng.choice(["VN", "DE", "IN"], n, p=[0.5, 0.3, 0.2]),
        "default": (rng.random(n) < 0.12).astype(int),
    })
    df.loc[[5, 17, 88], "age"] = [-1, 230, -1]
    df.loc[rng.choice(n, 14, replace=False), "income"] = np.nan
    df.loc[[30, 31], "country"] = ["vn", "Vietnam"]
    df.loc[150, "default"] = 2
    return pd.concat([df, df.iloc[[10, 11]]], ignore_index=True)

def fingerprint(df):
    return hashlib.sha256(pd.util.hash_pandas_object(df, index=False).values.tobytes()).hexdigest()[:12]

def build_report(df, findings, meta):
    label_counts = df[meta["label"]].value_counts().sort_index()
    worst = "error" if any(f["status"] == "error" for f in findings) else (
        "warning" if any(f["status"] == "warning" for f in findings) else "ok")
    decision = {"error": "NOT USABLE until the errors are fixed", "warning": "usable after review of the warnings",
                "ok": "usable"}[worst]
    lines = [
        f"# Data quality report: {meta['name']}",
        "",
        f"- data as of: {meta['as_of']} | fingerprint: `{fingerprint(df)}` | checks: v{meta['checks_version']}",
        f"- rows: {len(df)} | columns: {df.shape[1]} | one row = {meta['grain']}",
        "",
        "| check | status | rows | examples |",
        "|---|---|---|---|",
    ]
    lines += [f"| {f['check']} | {f['status']} | {f['rows']} | {'; '.join(f['examples'])} |" for f in findings]
    lines += ["", "label counts: " + ", ".join(f"{k}: {v}" for k, v in label_counts.items()),
              "", f"**Decision:** {decision}"]
    summary = {"fingerprint": fingerprint(df), "rows": len(df), "status": worst,
               "findings": {f["check"]: f["rows"] for f in findings}}
    return "\n".join(lines), summary

df = make_loans()
findings = [   # the results of the checks from the previous example
    {"check": "unique key", "status": "error", "rows": 4, "examples": ["L0010", "L0011"]},
    {"check": "column types", "status": "ok", "rows": 0, "examples": []},
    {"check": "missing values", "status": "warning", "rows": 14, "examples": ["income: 6.9%"]},
    {"check": "value ranges", "status": "warning", "rows": 3, "examples": ["age: [-1, 230, -1]"]},
    {"check": "allowed values", "status": "error", "rows": 3, "examples": ["country: ['Vietnam', 'vn']", "default: ['2']"]},
]
meta = {"name": "loan applications", "as_of": "2026-06-30", "checks_version": "1.0",
        "grain": "one loan application", "label": "default"}
report, summary = build_report(df, findings, meta)
print(report)
print()
print(json.dumps(summary))
# Data quality report: loan applications

- data as of: 2026-06-30 | fingerprint: `927d72763466` | checks: v1.0
- rows: 202 | columns: 5 | one row = one loan application

| check | status | rows | examples |
|---|---|---|---|
| unique key | error | 4 | L0010; L0011 |
| column types | ok | 0 |  |
| missing values | warning | 14 | income: 6.9% |
| value ranges | warning | 3 | age: [-1, 230, -1] |
| allowed values | error | 3 | country: ['Vietnam', 'vn']; default: ['2'] |

label counts: 0: 177, 1: 24, 2: 1

**Decision:** NOT USABLE until the errors are fixed

{"fingerprint": "927d72763466", "rows": 202, "status": "error", "findings": {"unique key": 4, "column types": 0, "missing values": 14, "value ranges": 3, "allowed values": 3}}

The report leads with the decision. Two findings are errors that block any use: the duplicated keys (L0010 and L0011 appear twice) and the impossible label value 2. The missing incomes (6.9% of rows, above the configured 5%) and the impossible ages are warnings: they need a decision, such as imputing incomes and setting placeholder ages to missing, but would not block the data on their own. The label counts show a second fact to keep in mind for training: only 24 defaults among 202 rows.

Comparing runs

Because the JSON summary has a fixed shape, two runs can be compared mechanically, for example last month's data against this month's, or the raw data against the cleaned data. A change in a finding's count is the first thing to look at:

python · try it yourself
before = {"fingerprint": "927d72763466", "rows": 202, "status": "error",
          "findings": {"unique key": 4, "column types": 0, "missing values": 14, "value ranges": 3, "allowed values": 3}}
# An illustrative later run, after duplicates, labels, countries and ages were fixed (incomes not yet imputed):
after = {"fingerprint": "5c41e09ab7d2", "rows": 200, "status": "warning",
         "findings": {"unique key": 0, "column types": 0, "missing values": 14, "value ranges": 0, "allowed values": 0}}

print(f"rows: {before['rows']} -> {after['rows']} | status: {before['status']} -> {after['status']}")
for check in before["findings"]:
    b, a = before["findings"][check], after["findings"][check]
    mark = "fixed" if a == 0 < b else ("better" if a < b else ("worse" if a > b else "same"))
    print(f"  {check:15} {b:3} -> {a:3}  {mark}")
rows: 202 -> 200 | status: error -> warning
  unique key        4 ->   0  fixed
  column types      0 ->   0  same
  missing values   14 ->  14  same
  value ranges      3 ->   0  fixed
  allowed values    3 ->   0  fixed

Run such a comparison automatically on every new batch of data, and fail the pipeline when an error appears or a count jumps: a data test, the data counterpart of a unit test. Tools such as Great Expectations, Soda, pandera or Evidently do this at scale, with HTML reports and dashboards; the structure is the one you have just built.

Making it reproducible

  • Code, not hand edits: the report is generated by a script under version control; any manual comment goes into a separate, clearly marked section.
  • Pinned inputs: the report states the dataset fingerprint and the version of the checks; the configuration is versioned with the code.
  • Deterministic output: fixed seeds, sorted outputs, no current timestamps, rounded numbers.
  • Stored with the data: save report.md and report.json next to the dataset version they describe.
  • Figures too: the plots from Visualising Data are saved as files by the same script and linked from the report.

Pitfalls

  • A report nobody reads: keep the top short (status, decision, the errors); put details below.
  • Changing checks silently: when a check changes, bump its version, or old and new reports cannot be compared.
  • Checking only once: data changes with every batch; run the checks every time, automatically.
  • Hiding judgement calls: thresholds such as "5% missing is a warning" are decisions; write them in the configuration where they can be seen and discussed.

Practice

  1. Add a check check_label_balance that returns a warning when the smallest class has less than 10% of the rows. What does it report for the loan data?
Answer
text
def check_label_balance(df, cfg):
    share = df[cfg["label"]].value_counts(normalize=True)
    small = share[share < 0.10]
    return "warning", int(df[cfg["label"]].isin(small.index).sum()), [f"{k}: {v:.1%}" for k, v in small.items()]

On the loan data it reports 1 row: class 2, the impossible label, with 0.5%. Class 1 has 24 of 202 rows (11.9%), just above the threshold. The impossible label is already an error from check_allowed, which shows why the results of all checks should be read together.

  1. Why must the report not contain the time it was generated, but should contain the date the data refers to?
Answer

The generation time changes on every run, so two reports on identical data would differ and could not be compared automatically. The data's own date (as of 30 June) is a property of the dataset version and belongs in the report.

Test yourself

What makes a data quality report reproducible?

  1. It is written carefully by hand
  2. It is generated by versioned code from a fixed dataset version, with deterministic output
  3. It contains many figures
  4. It is stored as a PDF

Why describe expectations (types, ranges, allowed values) as a configuration?

  1. It runs faster
  2. The checks stay the same while the expectations, which change per dataset, are visible, versioned and easy to review
  3. pandas requires it
  4. It removes the need for checks

A report finds duplicated keys and an impossible label value. Which status fits?

  1. ok
  2. info
  3. warning
  4. error: not usable until fixed