46 lines
1.8 KiB
Python
46 lines
1.8 KiB
Python
"""Validators a dataflow puts on its nodes. Nothing here does I/O or imports MLflow.
|
|
|
|
- `@checked_frame(schema)`: validates the node's frame with a pandera schema and fails the run if it doesn't hold. The
|
|
failure names the columns, the checks and how many rows failed, never the values: pandera's own report (and
|
|
`@check_output(schema=...)`) quotes them.
|
|
"""
|
|
|
|
from typing import Any
|
|
|
|
import pandas as pd
|
|
import pandera.pandas as pandera
|
|
from hamilton.data_quality.base import DataValidator, ValidationResult
|
|
from hamilton.function_modifiers import check_output_custom
|
|
|
|
|
|
class FrameCheck(DataValidator):
|
|
"""A pandera schema as a Hamilton validator whose message carries no data values."""
|
|
|
|
def __init__(self, schema: pandera.DataFrameSchema, importance: str = "fail"):
|
|
super().__init__(importance)
|
|
self.schema = schema
|
|
|
|
def applies_to(self, datatype: type) -> bool:
|
|
return issubclass(datatype, pd.DataFrame)
|
|
|
|
def description(self) -> str:
|
|
return f"rows satisfy {self.schema.name or 'the schema'}"
|
|
|
|
@classmethod
|
|
def name(cls) -> str:
|
|
return "frame_check"
|
|
|
|
def validate(self, dataset: Any) -> ValidationResult:
|
|
try:
|
|
self.schema.validate(dataset, lazy=True)
|
|
except pandera.errors.SchemaErrors as failed:
|
|
cases = failed.failure_cases.fillna({"column": "(frame)"})
|
|
counts = cases.groupby(["column", "check"], dropna=False).size()
|
|
summary = "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
|
|
return ValidationResult(False, f"{self.description()} doesn't hold: {summary}")
|
|
return ValidationResult(True, f"{self.description()}: holds")
|
|
|
|
|
|
def checked_frame(schema: pandera.DataFrameSchema):
|
|
return check_output_custom(FrameCheck(schema))
|