TECHNOLOGIESTieInn Technologies

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.contains passes partial matches; use fullmatch.
  • 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Data quality rules as Python functions

  1. Question 1easy

    Why should a data quality rule function return the failing rows rather than print a message?

  2. Data quality rules as Python functions

  3. Question 2easy

    Write unique(df, cols) returning every row whose key (the list of columns cols) appears more than once. Store len(unique(dw_orders, ["order_id"])) in result.

    The tables are ready as DataFrames with the same names. Store your answer in result.

    Tables
  4. Data quality rules as Python functions

  5. Question 3medium

    What does this print?

    import pandas as pd
    s = pd.Series(["UPI", "Wallet", None], dtype="string")
    print((~s.isin(["UPI", "Card"])).sum())
  6. Data quality rules as Python functions

  7. Question 4medium

    What does this print?

    orphans = dw_orders[~dw_orders["customer_id"].isin(dw_customers["customer_id"])]
    print(len(orphans))
  8. Data quality rules as Python functions

  9. 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)

2 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.