Data quality rules as Python functions
Data Quality Automation with Python · 7 questions
Short notes
Key idea
Write each data quality check as a function that takes a DataFrame and returns the rows that break the rule; an empty result means pass. Put the rules in a list, run them in a loop, and build a scorecard with PASS, FAIL or WARN. This is how Great Expectations and Soda work inside.
Syntax
not_null = lambda df, c: df[df[c].isna()]
unique = lambda df, cols: df[df.duplicated(cols, keep=False)]
allowed = lambda df, c, v: df[~df[c].isin(v)] # missing fails
in_range = lambda df, c, lo, hi: df[(df[c] < lo) | (df[c] > hi)]
matches = lambda df, c, p: df[~df[c].str.fullmatch(p).fillna(False)]
exists_in = lambda df, c, ref, rc: df[~df[c].isin(ref[rc])]
checks = [("dw_orders", "order_id unique",
lambda: unique(dw_orders, ["order_id"]), "error")]
Example
Shop scorecard: payment_method not null FAIL (1), order_id unique FAIL (4), customer exists FAIL (10), email masked FAIL (1), amount under 30000 WARN (4). Missing payment methods: 1.25%, over a 1% threshold.
Traps
- Printing instead of returning rows.
- Not deciding how missing values behave.
str.containspasses partial matches; usefullmatch.- Calling rules while building the list instead of wrapping them in
lambda.
Want the full lesson with step-by-step examples, a project and a certificate? Data Quality Automation with Python course, ₹120 →
- Question 1easy
Why should a data quality rule function return the failing rows rather than print a message?
- Question 2easy
Write
unique(df, cols)returning every row whose key (the list of columnscols) appears more than once. Storelen(unique(dw_orders, ["order_id"]))inresult.The tables are ready as DataFrames with the same names. Store your answer in
result.Tables
- Question 3medium
What does this print?
import pandas as pd s = pd.Series(["UPI", "Wallet", None], dtype="string") print((~s.isin(["UPI", "Card"])).sum())
- Question 4medium
What does this print?
orphans = dw_orders[~dw_orders["customer_id"].isin(dw_customers["customer_id"])] print(len(orphans))
- Question 5hard
The rule allows at most 1% missing payment methods. What does this print?
share = dw_orders["payment_method"].isna().mean() print(share > 0.01)
Data quality rules as Python functions
Data quality rules as Python functions
Data quality rules as Python functions
Data quality rules as Python functions
Data quality rules as Python functions
2 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.