Checking data automatically
Last updated
In project 3.P you checked the clean file with lines that printed True. That works if someone reads them. In this lesson you'll write checks that stop the program when data breaks a rule: assert statements, then a validate() function that lists every problem, run every time data loads.
By the end of this lesson you can
- Write
assertchecks on columns, ranges and keys - Write a
validate()function that reports every problem at once - Make checks part of loading, so they run every time
assert
assert checks that something is true. If it is, nothing happens. If not, the program stops with an AssertionError and your message. Run both cells.
January's clean file passes all three checks and prints its message. February's raw file fails the second: a kilos value outside 0 to 200. The notebook stops there, so nothing later can use the bad data.
Each assert is one rule, with a message saying which rule broke. Good rules to write for every table:
- the columns are the ones expected, in order;
- ranges: kilos between 0 and 200, dates in the month the file is for;
- keys are unique: no store, day and item twice;
- known values: every store is a known store;
- counts: no values missing, or at most a number you've agreed.
Two weaknesses: assert stops at the first failure, so you fix one problem, rerun, and meet the next. And Python skips every assert when it's run with python -O, so they're for checking your own work, not for checks that must always happen.
A validate() function
Here are the same rules and two more in a function that checks everything and returns a list of problems. Step through it, then run the cells.
validate(jan)returns[], an empty list: no problems.validate(feb)returns three:Lipa Cityisn't a known store, −9 kilos, and a repeated row. All three at once, so you can fix them together.load_salesreads a file and validates it, and raises aValueErrorlisting every problem if there are any. If every notebook loads data withload_salesinstead ofread_csv, the checks run every time, on every file, without anyone having to remember.
raise ValueError(...) always runs, even with python -O, which is why the loader uses it instead of assert.
Schemas with pandera
As rules grow, a library helps. pandera describes a table's schema, its columns, types and rules, and checks a DataFrame against it. It isn't loaded in this page; on your computer, python -m pip install pandera:
import pandera.pandas as pa
sales_schema = pa.DataFrameSchema(
{
"date": pa.Column("datetime64[ns]"),
"store": pa.Column(str, pa.Check.isin(["Batangas", "Lipa", "Tanauan"])),
"item": pa.Column(str),
"kilos": pa.Column(float, pa.Check.in_range(0, 200)),
},
unique=["date", "store", "item"],
strict=True,
)
sales_schema.validate(sales, lazy=True)lazy=True collects every failure, like validate() did, instead of stopping at the first. strict=True fails if there's a column the schema doesn't name. The schema reads as documentation too: anyone can see what a clean sales table promises.
Wrong way: a check written once
February's report showed Lipa selling nothing for a week. The cause: the file spelled it Lipa City, so Lipa's rows never matched. You find it, fix it, and add a cell at the bottom of that month's notebook:
print(sales["store"].isin(STORES).all()) # True nowIn April, a new staff member types LIPA. The check is still at the bottom of February's notebook, which nobody runs again. April's report goes out with Lipa missing again.
A check only protects you if it runs every time data comes in, and stops when it fails instead of printing False for someone to notice. Put each new rule in validate(), where load_sales runs it on every file from then on. Every bug you find should leave a rule behind.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Language Reference: The assert statement: and why python -O skips it
- pandera documentation: schemas for DataFrames
- Wilson et al., Good enough practices in scientific computing, PLOS Computational Biology, 2017: check data as it comes in