Data analysis · Intermediate · 18 min
Validate data with pandera before you analyse it
By Padding · Updated 18 Nov 2026
Python 3.15 · pandera 0.36.0 · pandas 3.1.1 · pytest 9.2.0 · uv 0.13 (checked on python:3.15-slim)
You will have a pandera 0.36 schema that checks each monthly sales export, writes every problem to a CSV a colleague can fix, and runs in pytest so a broken file stops the report before it starts.
On this page
An analysis is only as good as the file it starts from. When a monthly export arrives with a typo in a region, an order entered twice or a row from next month, pandas reads it without complaint and the totals come out wrong but plausible. Nobody notices until a branch manager asks why their number looks odd.
pandera lets you write down what a good file looks like, once, as a schema: which columns exist, their types, which values are allowed, what must be unique and which dates belong in the month. You then check every file against it before any analysis runs.
In this tutorial you build that for a company with branches in Lagos, Accra, Nairobi and Kampala that sends one sales export per month. By the end you have:
schema.py, the schema, with one custom check of your ownload.py, which reads an export and validates itvalidate.py, a command that writes every problem in a file to a CSV someone can work through- a pytest file, so a broken export fails the tests and the report never runs on it
Step 1 · Create the project
Make a demo folder and add pandera with its pandas extra, pandas itself and pytest. Since version 0.24 pandera installs its pandas support as an extra, so the [pandas] part matters. The ranges allow patch releases and nothing newer:
mkdir -p ~/pandera-demo
cd ~/pandera-demo
uv init --no-package
rm -f main.py
uv add "pandera[pandas]>=0.36,<0.37" "pandas>=3.1,<3.2" "pytest>=9.2,<9.3"uv init writes a starter main.py that this project does not use, so the second-last line removes it.
Check it worked
uv run python -c "import pandera, pandas, pytest; print(pandera.__version__, pandas.__version__, pytest.__version__)"The output is 0.36.0 3.1.1 9.2.0, or later patch releases of each.
Step 2 · Add two monthly exports
Exports land in incoming/, named sales-YYYY-MM.csv. September is clean. October has the kinds of mistakes real exports have: a misspelt region, a negative amount, an order id used twice, an order dated in November, and a Kampala order marked as West region:
mkdir -p incoming
cat > incoming/sales-2026-09.csv <<'CSV'
order_id,order_date,branch,region,amount
LOS-0901,2026-09-04,Lagos,West,40.00
LOS-0902,2026-09-22,Lagos,West,135.00
ACC-0901,2026-09-12,Accra,West,31.50
NBO-0901,2026-09-11,Nairobi,East,64.00
KLA-0901,2026-09-30,Kampala,East,18.75
CSV
cat > incoming/sales-2026-10.csv <<'CSV'
order_id,order_date,branch,region,amount
LOS-1001,2026-10-02,Lagos,West,125.50
LOS-1002,2026-10-09,Lagos,West,60.00
ACC-1001,2026-10-05,Accra,Wset,88.20
NBO-1001,2026-10-03,Nairobi,East,-240.00
NBO-1001,2026-10-15,Nairobi,East,19.99
KLA-1001,2026-11-01,Kampala,East,72.40
KLA-1002,2026-10-30,Kampala,West,15.00
CSVLoad October with plain pandas and add it up, the way an analysis would:
uv run python -c "import pandas as pd; df = pd.read_csv('incoming/sales-2026-10.csv'); print(len(df), 'rows, total', round(df['amount'].sum(), 2))"Check it worked
The output is 7 rows, total 141.09. pandas reported no problem at all, yet the total is wrong in three ways: it subtracts 240 instead of adding it, it counts a November order, and it may count a duplicate order. That is the gap the schema closes.
Step 3 · Write the schema
Create schema.py. The schema is built by a function that takes the month, because the allowed date range changes every month:
cat > schema.py <<'PY'
import calendar
import pandas as pd
import pandera.pandas as pa
BRANCH_REGIONS = {"Lagos": "West", "Accra": "West", "Nairobi": "East", "Kampala": "East"}
def sales_schema(month: str) -> pa.DataFrameSchema:
year, number = (int(part) for part in month.split("-"))
first_day = pd.Timestamp(year, number, 1)
last_day = pd.Timestamp(year, number, calendar.monthrange(year, number)[1])
return pa.DataFrameSchema(
{
"order_id": pa.Column(str, pa.Check.str_matches(r"^[A-Z]{3}-\d{4}$"), unique=True),
"order_date": pa.Column("datetime64[ns]", pa.Check.in_range(first_day, last_day)),
"branch": pa.Column(str, pa.Check.isin(list(BRANCH_REGIONS))),
"region": pa.Column(str, pa.Check.isin(["East", "West"])),
"amount": pa.Column(float, pa.Check.ge(0)),
},
coerce=True,
strict=True,
name=f"sales {month}",
)
PYEach line states one rule about the file:
order_idis text in the shapeABC-1234, andunique=Truerejects an id used more than once.order_datebecomes a real date and must fall between the first and last day of the month.calendar.monthrangegives the number of days, so February and leap years are handled.branchandregionmust be one of a fixed list. A typo such asWsetfails instead of becoming a fifth region in your charts.amountis a number of zero or more. Refunds, if your business has them, belong in their own column or file, where they can be checked on purpose.coerce=Trueconverts each column to the type named, so you can read the CSV as text and let the schema do the conversion. A value that cannot be converted is reported, not silently turned into a missing value.strict=Truerejects columns the schema does not name, so an export with an extra or renamed column fails instead of passing with the wrong data.
Columns are nullable=False by default, so an empty cell in any column is also a failure.
Now create load.py, the one place exports are read. It reads every column as text, works out the month from the file name and validates:
cat > load.py <<'PY'
import re
from pathlib import Path
import pandas as pd
from schema import sales_schema
def month_of(path: Path) -> str:
found = re.fullmatch(r"sales-(\d{4}-(0[1-9]|1[0-2]))\.csv", path.name)
if not found:
raise ValueError(f"{path.name} is not named sales-YYYY-MM.csv")
return found.group(1)
def load_sales(path: Path) -> pd.DataFrame:
raw = pd.read_csv(path, dtype=str, encoding="utf-8-sig")
return sales_schema(month_of(path)).validate(raw, lazy=True)
PYencoding="utf-8-sig" reads plain UTF-8 and also the UTF-8 files Excel saves with a hidden marker at the start, which would otherwise stick to the first column name and make strict=True fail on order_id. It also keeps branch or customer names in other scripts and accents intact, such as a Yoruba or Amharic name typed in at a branch. lazy=True is explained in the next step.
Check it worked
Validate September and look at the column types that come back:
uv run python -c "from pathlib import Path; from load import load_sales; d = load_sales(Path('incoming/sales-2026-09.csv')); print(len(d), 'rows'); print(d.dtypes.to_string())"The output is:
5 rows
order_id str
order_date datetime64[ns]
branch str
region str
amount float64The file went in as text and came out with real dates and numbers, ready to analyse.
Step 4 · Collect every failure at once
By default pandera stops at the first failed rule. That is fine in code, but for a data file it means fixing one problem, re-running, finding the next, and asking the branch for a new export each time. Compare the two modes on October:
uv run python - <<'PY'
import pandas as pd
import pandera.pandas as pa
from schema import sales_schema
raw = pd.read_csv("incoming/sales-2026-10.csv", dtype=str)
schema = sales_schema("2026-10")
try:
schema.validate(raw)
except pa.errors.SchemaError as err:
print("First failure only:", str(err).splitlines()[0])
try:
schema.validate(raw, lazy=True)
except pa.errors.SchemaErrors as err:
print(err.failure_cases[["column", "check", "failure_case", "index"]].to_string(index=False))
PYCheck it worked
The eager run stops at the first rule broken, the duplicate id. The lazy run lists every failure:
First failure only: series 'order_id' contains duplicate values:
column check failure_case index
order_id field_uniqueness NBO-1001 3
order_id field_uniqueness NBO-1001 4
order_date in_range(2026-10-01 00:00:00, 2026-10-31 00:00:00) 2026-11-01 00:00:00 5
region isin(['East', 'West']) Wset 2
amount greater_than_or_equal_to(0) -240.0 3With lazy=True pandera raises SchemaErrors (plural), and its failure_cases attribute is an ordinary DataFrame: one row per failing value, with the column, the rule it broke, the value and the row's position in the DataFrame. index counts from 0 and skips the header, so index 2 is line 4 of the file. The next step turns it into something a colleague can use. The Kampala row marked West is not caught yet; no built-in rule can see that.
Step 5 · Write the failures to a CSV a colleague can act on
The person who fixes the export usually opens it in a spreadsheet, not Python. Give them a file with the line number they will see, the order id, the column, the rule and the bad value. Create validate.py:
cat > validate.py <<'PY'
import sys
from pathlib import Path
import pandas as pd
import pandera.pandas as pa
from load import load_sales
def failure_table(err: pa.errors.SchemaErrors, path: Path) -> pd.DataFrame:
cases = err.failure_cases
raw = pd.read_csv(path, dtype=str, encoding="utf-8-sig")
rows = pd.to_numeric(cases["index"], errors="coerce").astype("Int64")
whole_row = cases["schema_context"] == "DataFrameSchema"
table = pd.DataFrame(
{
"line": rows + 2, # +1 for the header row, +1 because lines count from 1
"order_id": rows.map(raw["order_id"]),
"column": cases["column"].where(~whole_row, "(whole row)"),
"problem": cases["check"],
"value": cases["failure_case"].where(~whole_row, ""),
}
)
return table.drop_duplicates(["line", "problem"]).sort_values(["line", "column"], ignore_index=True)
def main(path_text: str) -> int:
path = Path(path_text)
try:
sales = load_sales(path)
except pa.errors.SchemaErrors as err:
table = failure_table(err, path)
out = Path("failures") / f"{path.stem}-failures.csv"
out.parent.mkdir(exist_ok=True)
table.to_csv(out, index=False)
print(f"{path.name}: {len(table)} problem(s) on {table['line'].nunique()} line(s), written to {out}")
return 1
print(f"{path.name}: {len(sales)} rows passed")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))
PY
uv run validate.py incoming/sales-2026-09.csv
uv run validate.py incoming/sales-2026-10.csv || echo "exit code $?"What the code does with pandera's table:
- Line numbers. The DataFrame position plus 2 is the line in the CSV file, which is what a spreadsheet shows on the left.
- The order id is looked up from the original file, so the colleague can search for it in their own system.
- Whole-row rules. A check on the whole DataFrame, like the one in the next step, lists every cell of a failing row. The code keeps one line per row per rule and marks it
(whole row). - Rules that could not run. If a value cannot be converted at all, pandera reports it on its line, and the rules for that column report an error with no row.
pd.to_numeric(..., errors="coerce")keeps those as blank lines instead of crashing. - Exit codes. The command exits 1 when the file has problems and 0 when it passes, so a script or scheduler can stop on it.
The failures go in their own failures/ folder, never in incoming/, so they are not mistaken for an export.
Check it worked
The output is sales-2026-09.csv: 5 rows passed, then sales-2026-10.csv: 5 problem(s) on 4 line(s), written to failures/sales-2026-10-failures.csv and exit code 1. Look at the file:
cat failures/sales-2026-10-failures.csvline,order_id,column,problem,value
4,ACC-1001,region,"isin(['East', 'West'])",Wset
5,NBO-1001,amount,greater_than_or_equal_to(0),-240.0
5,NBO-1001,order_id,field_uniqueness,NBO-1001
6,NBO-1001,order_id,field_uniqueness,NBO-1001
7,KLA-1001,order_date,"in_range(2026-10-01 00:00:00, 2026-10-31 00:00:00)",2026-11-01 00:00:00Open it in a spreadsheet app and every row points at a line in the export. Lines 5 and 6 both appear for the duplicate, because only the branch knows which of the two orders is the real NBO-1001.
Try a value that cannot be converted. Exports from a computer set to French or Portuguese often write amounts with a decimal comma:
cat > sales-2026-12.csv <<'CSV'
order_id,order_date,branch,region,amount
ACC-1201,2026-12-02,Accra,West,"12,50"
CSV
uv run validate.py sales-2026-12.csv || echo "exit code $?"
cat failures/sales-2026-12-failures.csvLine 2 is reported twice, as coerce_dtype('float64') and dtype('float64') with the value 12,50, followed by a line with no line number for the ge(0) rule, whose value is a TypeError because the rule could not run on text. Fix the conversion problems first; the other rules for that column run once the value is a number.
Remove the test file and its failures:
rm sales-2026-12.csv failures/sales-2026-12-failures.csvStep 6 · Add a custom check
Built-in checks look at one column at a time. Some rules need two: each branch belongs to one region, and an export that puts Kampala in the West region is wrong even though both values are allowed. A custom check is a function that takes the DataFrame and returns True or False per row. Replace schema.py with this version, which adds branch_in_its_region and passes it in checks=:
cat > schema.py <<'PY'
import calendar
import pandas as pd
import pandera.pandas as pa
BRANCH_REGIONS = {"Lagos": "West", "Accra": "West", "Nairobi": "East", "Kampala": "East"}
def branch_in_its_region(sales: pd.DataFrame) -> pd.Series:
return sales["branch"].map(BRANCH_REGIONS) == sales["region"]
def sales_schema(month: str) -> pa.DataFrameSchema:
year, number = (int(part) for part in month.split("-"))
first_day = pd.Timestamp(year, number, 1)
last_day = pd.Timestamp(year, number, calendar.monthrange(year, number)[1])
return pa.DataFrameSchema(
{
"order_id": pa.Column(str, pa.Check.str_matches(r"^[A-Z]{3}-\d{4}$"), unique=True),
"order_date": pa.Column("datetime64[ns]", pa.Check.in_range(first_day, last_day)),
"branch": pa.Column(str, pa.Check.isin(list(BRANCH_REGIONS))),
"region": pa.Column(str, pa.Check.isin(["East", "West"])),
"amount": pa.Column(float, pa.Check.ge(0)),
},
checks=[pa.Check(branch_in_its_region, name="branch_in_its_region")],
coerce=True,
strict=True,
name=f"sales {month}",
)
PY
uv run validate.py incoming/sales-2026-10.csv || echo "exit code $?"
cat failures/sales-2026-10-failures.csvThe mapping of branches to regions lives in one dictionary, BRANCH_REGIONS, which both the custom check and the branch rule use. When a fifth branch opens, you add it there and nowhere else. name= is what appears in the problem column, so choose one that a colleague can read.
Check it worked
The output is now 7 problem(s) on 5 line(s), and the failures file has two new rows:
line,order_id,column,problem,value
4,ACC-1001,(whole row),branch_in_its_region,
4,ACC-1001,region,"isin(['East', 'West'])",Wset
5,NBO-1001,amount,greater_than_or_equal_to(0),-240.0
5,NBO-1001,order_id,field_uniqueness,NBO-1001
6,NBO-1001,order_id,field_uniqueness,NBO-1001
7,KLA-1001,order_date,"in_range(2026-10-01 00:00:00, 2026-10-31 00:00:00)",2026-11-01 00:00:00
8,KLA-1002,(whole row),branch_in_its_region,Line 8 is the Kampala order marked West, which no built-in rule caught. Line 4 fails both rules, because Wset is not a region at all and so cannot be Accra's region either.
Step 7 · Run the schema in pytest
A schema only protects you if it runs every time. Putting it in the test suite means a broken export fails pytest and the report command after it never starts. Tell pytest where the code and tests are, by adding a section to pyproject.toml:
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
TOMLThen create tests/test_sales_files.py. It checks every export in incoming/, one test per file, and also tests the custom rule on a tiny DataFrame, so you know the rule itself works:
mkdir -p tests
cat > tests/test_sales_files.py <<'PY'
from pathlib import Path
import pandas as pd
import pandera.pandas as pa
import pytest
from load import load_sales
from schema import sales_schema
INCOMING = Path(__file__).resolve().parent.parent / "incoming"
EXPORTS = sorted(INCOMING.glob("sales-*.csv"))
def test_there_are_exports_to_check():
assert EXPORTS, f"no sales-*.csv files in {INCOMING}"
@pytest.mark.parametrize("path", EXPORTS, ids=lambda path: path.name)
def test_export_matches_schema(path):
load_sales(path)
def test_schema_catches_a_branch_in_the_wrong_region():
bad = pd.DataFrame(
{
"order_id": ["LOS-0001"],
"order_date": ["2026-10-01"],
"branch": ["Lagos"],
"region": ["East"],
"amount": ["10.00"],
}
)
with pytest.raises(pa.errors.SchemaErrors) as caught:
sales_schema("2026-10").validate(bad, lazy=True)
assert set(caught.value.failure_cases["check"]) == {"branch_in_its_region"}
PYtest_there_are_exports_to_check matters more than it looks: if someone moves the folder, the parametrised test would otherwise run zero times and pass.
Now add a small report, the analysis the checks protect. Create report.py:
cat > report.py <<'PY'
import sys
from pathlib import Path
from load import load_sales
month = sys.argv[1]
sales = load_sales(Path("incoming") / f"sales-{month}.csv")
by_branch = sales.groupby("branch")["amount"].agg(orders="count", revenue="sum")
print(f"Sales by branch, {month}")
print(by_branch.round(2).to_string())
PY
uv run pytest -q && uv run report.py 2026-10 || echo "stopped with exit code $?"&& runs the report only when every test passes.
Check it worked
pytest prints a long traceback that ends in pandera's summary of every failure, grouped by kind, then a last line that starts 1 failed, 3 passed. The failed test is named test_export_matches_schema[sales-2026-10.csv], so you know which file to look at. The report never prints, and the shell shows stopped with exit code 1.
Step 8 · Replace the export and run the report
Send failures/sales-2026-10-failures.csv to the person who made the export. Here is their corrected file: the region is spelt correctly, the refund was a typo for 240.00, the second Nairobi order gets its own id, the November order is removed (it belongs in next month's file) and the Kampala order is marked East:
cat > incoming/sales-2026-10.csv <<'CSV'
order_id,order_date,branch,region,amount
LOS-1001,2026-10-02,Lagos,West,125.50
LOS-1002,2026-10-09,Lagos,West,60.00
ACC-1001,2026-10-05,Accra,West,88.20
NBO-1001,2026-10-03,Nairobi,East,240.00
NBO-1002,2026-10-15,Nairobi,East,19.99
KLA-1002,2026-10-30,Kampala,East,15.00
CSV
uv run validate.py incoming/sales-2026-10.csv
uv run pytest -q && uv run report.py 2026-10Do not edit an export yourself to make it pass unless you know the right value. A corrected file from its source keeps the branch's own records and yours in agreement.
Check it worked
validate.py prints sales-2026-10.csv: 6 rows passed, pytest's last line starts 4 passed, and the report prints:
Sales by branch, 2026-10
orders revenue
branch
Accra 1 88.20
Kampala 1 15.00
Lagos 2 185.50
Nairobi 2 259.99The old failures file is still in failures/; delete it once the corrected export passes, so nobody acts on it again.
Step 9 · Clean up
Remove the demo project. Python and uv stay installed:
cd ~
rm -rf ~/pandera-demoCheck it worked
ls ~/pandera-demo reports that there is no such file or directory.
Next steps
- Fix the problems a schema finds, such as stray spaces and mixed date formats, before validating: clean a CSV file with pandas.
- Put the validated data into a formatted monthly workbook: automate a monthly Excel report with Python.
- Learn more about fixtures, parametrisation and reading test failures: test Python code with pytest.
- Pin every package so the checks behave the same next year: make a data analysis reproducible.
Part of these paths
Related tutorials
- How to Clean and Summarise a CSV File with pandasYou will take a messy orders CSV with stray spaces, mixed spellings, money written as text, odd dates, missing values and a duplicate row, and clean it with pandas 3.1 on Python 3.15 into a tidy file plus per-country and per-month summaries.
- Automate a monthly Excel report with PythonYou will replace a copy-and-paste monthly report with one command that checks each branch's CSV file, builds a summary in pandas 3.1 and writes a formatted Excel workbook with a native chart, named by month.
- How to Write and Run Tests in Python with pytestYou will install pytest 9.2 in a uv project, write tests for a small price-parsing module, run many cases from one test with parametrize, read a failure and fix the code, and use a fixture that gives each test its own temporary folder.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials