API reference
This page is generated from the package docstrings. Every public name is importable directly from data_cleaner.
from data_cleaner import DataCleaner, audit_split, validate| Object | Use it for |
|---|---|
DataCleaner | Fit cleaning rules on training data and transform later batches |
CleanerConfig | Configure imputation, outliers, datetime features, contracts, and drift policy |
DataContract | Declare column roles, allowed values, ranges, patterns, and uniqueness |
read_csv_safe | Read CSV as text, coerce under a contract, and audit the conversion |
iter_csv_safe | Stream a large CSV in typed chunks with one audit report per chunk |
combine_ingestion_reports | Roll per-chunk ingestion reports into one whole-file report |
read_excel_safe | Read one Excel sheet with the same guards and audit report |
read_parquet_safe | Read Parquet under a contract with the same audit report (PyArrow extra) |
iter_parquet_safe | Stream a large Parquet file in audited record batches |
combine_drift_reports | Roll per-chunk drift reports into one run-level TransformReport |
CleanerReport | Combine profile, contract, validation, ingestion, and decisions for one batch |
validate | Evaluate reusable expectations and rules against a DataFrame |
compare_distributions | Compare a batch against a reference distribution with PSI and Wasserstein distance |
JsonlReportSink | Keep an append-only batch history and compare against a stored reference |
audit_split | Check a train/test split for leakage before training |
The usual path is CleanerConfig → DataCleaner.fit() → DataCleaner.transform(). Contracts, validation, and the split audit are independent tools you can adopt incrementally.
data_cleaner.DataCleaner
Bases: TransformerMixin, BaseEstimator
Fit/transform data cleaner that prevents train/test leakage.
The cleaner learns imputers, outlier bounds, category policies and schema information on training data, then applies exactly those learned rules to validation, test, or inference batches.
fit
fit(X: pd.DataFrame, y: object | None = None) -> DataCleanerLearn cleaning rules from training data.
transform
transform(X: pd.DataFrame) -> pd.DataFrameApply learned cleaning rules without fitting anything.
The findings for this batch are also stored on the instance and can be read with drift_report. That attribute is per-instance last-transform state, so concurrent calls can overwrite it. Use transform_with_report when you need the report that belongs to exactly one batch.
transform_with_report
transform_with_report(X: pd.DataFrame) -> tuple[pd.DataFrame, DriftReport]Clean X and return the frame together with its drift report.
Unlike transform, this method does not read or write the shared drift_report_ state, so it is safe to call concurrently on one fitted cleaner from multiple threads or batch workers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | pd.DataFrame | Inference batch. It is never mutated and no rows are dropped. | required |
Returns:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, DriftReport] | The cleaned frame and the contract findings for this batch. |
transform_chunks
transform_chunks(chunks: Iterable[pd.DataFrame]) -> Iterator[tuple[pd.DataFrame, DriftReport]]Clean a stream of frames and yield each result with its own report.
This is the chunked counterpart to transform_with_report. It keeps one chunk in memory at a time, never writes shared instance state, and is safe to consume from concurrent workers as long as each worker owns its iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks | Iterable[pd.DataFrame] | Iterable of DataFrames, usually produced by | required |
Yields:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, DriftReport] | The cleaned chunk and its findings. |
Examples:
>>> cleans = cleaner.transform_chunks(frame for frame, _ in chunks)
>>> for cleaned, report in cleans:
... store(cleaned)fit_transform
fit_transform(X: pd.DataFrame, y: object | None = None) -> pd.DataFrameFit on X and return the cleaned training DataFrame.
get_feature_names_out
get_feature_names_out(input_features: list[str] | None = None) -> np.ndarrayReturn cleaned output column names.
cleaning_summary
cleaning_summary() -> pd.DataFrameReturn a learned cleaning summary for auditing/debugging.
outlier_summary
outlier_summary() -> pd.DataFrameReturn outlier bounds learned for numeric columns.
drift_report
drift_report() -> pd.DataFrameReturn the column-contract drift findings seen at the last transform.
fitted_contract
fitted_contract() -> DataContract | NoneReturn the contract used by this fitted cleaner.
decision_log
decision_log() -> pd.DataFrameReturn one row per learned or configured cleaning decision.
fingerprint
fingerprint(X: pd.DataFrame) -> strReturn a stable schema + statistics fingerprint for X.
to_manifest
to_manifest(X: pd.DataFrame | None = None, *, include_fingerprint: bool = False) -> dict[str, object]Return a JSON-serializable manifest describing this fitted cleaner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | pd.DataFrame | None | Optional frame to fingerprint. When omitted and | None |
include_fingerprint | bool | Include a | False |
Raises:
| Type | Description |
|---|---|
ValueError | If a fingerprint is requested but none can be computed. |
artifact_manifest
artifact_manifest(X: pd.DataFrame | None = None, *, include_fingerprint: bool = False) -> dict[str, object]Return the manifest stored in the artifact, or build a fresh one.
After load, this returns the manifest captured when the artifact was saved. For a fitted-but-unsaved cleaner it falls back to to_manifest.
save
save(path: str | Path) -> PathPersist the fitted cleaner and its manifest as a joblib artifact.
The artifact is written to a temporary file in the destination directory, read back to validate it, and then atomically moved into place with os.replace. An interrupted or failed save never leaves a truncated artifact at path, and partial files are removed.
load
load(path: str | Path, verify_version: bool = True, *, allow_incompatible: bool = False, strict_environment: bool = False) -> DataCleanerLoad a saved cleaner artifact and restore its manifest.
Artifacts written by a different artifact format version or a different library major version are refused by default. Pass allow_incompatible=True to load them with a warning, or verify_version=False to skip the compatibility check entirely. joblib.load uses pickle, so only load artifacts you trust.
The manifest records the pandas, NumPy, and scikit-learn versions used when the artifact was written. A major-version mismatch logs a warning by default; pass strict_environment=True to raise ArtifactCompatibilityError instead.
data_cleaner.CleanerConfigdataclass
Configuration for DataCleaner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numeric_imputation | Literal['median', 'mean', 'constant'] | 'median' | |
categorical_imputation | Literal['mode', 'constant'] | 'mode' | |
numeric_fill_value | float | 0.0 | |
categorical_fill_value | str | 'Unknown' | |
cap_outliers | bool | False | |
outlier_multiplier | float | 1.5 | |
outlier_columns | tuple[str, ...] | () | |
add_missing_indicators | bool | False | |
drop_constant_columns | bool | True | |
numeric_columns | tuple[str, ...] | () | |
categorical_columns | tuple[str, ...] | () | |
datetime_columns | tuple[str, ...] | () | |
datetime_features | tuple[str, ...] | ('year', 'month', 'day', 'dayofweek', 'is_weekend') | |
unseen_category | Literal['keep', 'fill'] | 'keep' | |
preserve_integer_dtypes | bool | True | |
on_precision_loss | Literal['raise', 'warn', 'coerce'] | 'coerce' | |
contract | DataContract | None | None | |
on_drift | Literal['raise', 'warn', 'ignore'] | 'warn' | |
infer_contract | bool | True | |
fingerprint_on_fit | bool | False | |
verbose | bool | True |
data_cleaner.CleaningDecisiondataclass
A single auditable cleaning decision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column | str | Source column the decision applies to, or | required |
action | str | Short, machine-readable verb, for example | required |
reason | str | Human-readable explanation of why the action was taken. | required |
source | str | Where the rule came from: | required |
before | object | Optional description of the state before the decision. | None |
after | object | Optional description of the state after the decision. | None |
to_dict
to_dict() -> dict[str, object]Return a JSON-serializable representation of the decision.
data_cleaner.ColumnSpecdataclass
Declarative expectations and semantics for a single column.
role tells the cleaner how the column should be treated (numeric, category, boolean, datetime, id, text, ignore). The remaining fields describe optional contract checks. required=False marks a column that may be absent from the training frame; role="ignore" columns are always treated as optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | required | |
role | str | None | None | |
dtype | str | None | None | |
nullable | bool | True | |
unique | bool | False | |
allowed_values | tuple[object, ...] | None | None | |
min_value | float | None | None | |
max_value | float | None | None | |
pattern | str | None | None | |
date_format | str | None | None | |
preserve_leading_zeros | bool | False | |
severity | Literal['error', 'warning'] | 'error' | |
required | bool | True |
to_dict
to_dict() -> dict[str, object]Return a JSON-serializable representation of the spec.
from_dict
from_dict(data: dict[str, object]) -> ColumnSpecRebuild a spec from to_dict output.
data_cleaner.DataContractdataclass
A set of ColumnSpec objects describing expected input columns.
strict=True also reports columns present in the frame but not declared in the contract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns | tuple[ColumnSpec, ...] | () | |
strict | bool | False |
spec_for
spec_for(name: str) -> ColumnSpec | NoneReturn the spec for name, or None when it is not declared.
infer_from
infer_from(frame: pd.DataFrame, config: CleanerConfig | None = None, strict: bool = True) -> DataContractInfer a conservative contract from a training frame.
from_frame
from_frame(frame: pd.DataFrame, config: CleanerConfig | None = None, strict: bool = True) -> DataContractInfer a contract from frame (alias for infer_from).
validate
validate(frame: pd.DataFrame) -> ValidationReportCheck frame against this contract and return a validation report.
check
check(frame: pd.DataFrame) -> DriftReportCompare frame against the contract and collect every difference.
to_dict
to_dict() -> dict[str, object]Return a JSON-serializable representation of the contract.
from_dict
from_dict(data: dict[str, object]) -> DataContractRebuild a contract from to_dict output.
to_json
to_json(**kwargs: object) -> strSerialize the contract to JSON.
from_json
from_json(text: str) -> DataContractParse a contract from JSON.
to_yaml
to_yaml() -> strSerialize to YAML (requires the optional pyyaml package).
from_yaml
from_yaml(text: str) -> DataContractParse YAML (requires the optional pyyaml package).
data_cleaner.DriftReportdataclass
Bases: _FindingsMixin
Column-contract findings for a single transform batch.
rows is the number of rows in the batch that produced these findings. It lets combine_drift_reports reconstruct a run-level row count without holding on to the cleaned frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
findings | pd.DataFrame | required | |
rows | int | 0 |
empty
empty() -> DriftReportdata_cleaner.TransformReportdataclass
Bases: _FindingsMixin
Aggregated findings for a chunked transform run.
Returned by combine_drift_reports. It exposes the same has_drift, errors, warnings, summary(), and raise_if_errors() surface as DriftReport, plus the total row and chunk counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
findings | pd.DataFrame | required | |
rows | int | 0 | |
chunks | int | 0 |
empty
empty() -> TransformReportto_dict
to_dict() -> dict[str, object]Return a JSON-friendly summary of the aggregated run.
data_cleaner.combine_drift_reports
combine_drift_reports(reports: Iterable[DriftReport]) -> TransformReportRoll per-chunk DriftReport objects into one run-level report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reports | Iterable[DriftReport] | Reports from | required |
Returns:
| Type | Description |
|---|---|
TransformReport | Findings concatenated in chunk order, with summed |
Notes:
Findings are concatenated, not deduplicated: two chunks with the same drift produce two rows. That keeps the aggregate faithful to what happened per chunk and lets downstream code count occurrences by summing.
Contract is a shorthand alias for DataContract.
read_excel_safe requires the optional excel extra (openpyxl for .xlsx and .xlsm). read_parquet_safe and iter_parquet_safe require the optional parquet extra (pyarrow). read_csv_safe and iter_csv_safe have no extra dependency.
data_cleaner.IngestionReportdataclass
Audit report returned by read_csv_safe or read_excel_safe.
findings is a tidy DataFrame with column, check, severity, message, and count columns. columns summarizes how each input column was detected and typed. Neither table includes raw cell values.
sheet is the resolved worksheet name for Excel input and None for CSV input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | required | |
rows | int | required | |
columns | pd.DataFrame | required | |
findings | pd.DataFrame | required | |
sheet | str | None | None |
location
Source label, including the resolved sheet for Excel input.
success
Whether ingestion found no error-severity issues.
errors
Findings with error severity.
warnings
Findings with warning severity.
has_errors
Whether at least one error-severity finding exists.
has_warnings
Whether at least one warning-severity finding exists.
summary
summary() -> strReturn a short human-readable description of the findings.
to_markdown
to_markdown() -> strRender the findings as a Markdown table (falls back to text).
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the report.
raise_if_failed
raise_if_failed(message: str = 'Ingestion failed') -> NoneRaise IngestionError when an error-severity finding exists.
data_cleaner.IngestionError
Bases: ValueError
Raised when ingestion finds error-severity issues and policy is raise.
data_cleaner.read_csv_safe
read_csv_safe(source: str | os.PathLike[str] | IO[Any], contract: DataContract | None = None, *, on_error: IngestionPolicy = 'warn', **read_csv_kwargs: Any) -> tuple[pd.DataFrame, IngestionReport]Read a CSV as text, coerce it under an optional contract, and audit it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | os.PathLike[str] | IO[Any] | Path or file-like object accepted by | required |
contract | DataContract | None | Optional | None |
on_error | IngestionPolicy |
| 'warn' |
**read_csv_kwargs | Any | Extra options passed to | required |
Returns:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, IngestionReport] | The typed frame and an audit report. String columns are kept as |
Notes:
The reader recognizes common spreadsheet spellings: thousands separators, currency symbols, percent signs, accounting parentheses, decimal commas, YYYYMMDD dates, Excel serial dates, and Y/N-style booleans. Normalization is reported, never performed silently. Values that cannot be parsed in a declared numeric/date/boolean column become missing values and produce an error finding.
Identifier columns and columns with leading zeros are kept as text. Passing a contract is the safest way to protect identifiers and to make date formats unambiguous.
This function reads the whole file into memory. For large files, use iter_csv_safe, which yields typed chunks and a per-chunk report.
data_cleaner.iter_csv_safe
iter_csv_safe(source: str | os.PathLike[str] | IO[Any], contract: DataContract | None = None, *, chunksize: int = 100000, on_error: IngestionPolicy = 'warn', unique_tracking: Literal['memory', 'disk', 'auto'] = 'auto', unique_tracking_limit: int = 1000000, unique_tracking_path: str | os.PathLike[str] | None = None, **read_csv_kwargs: Any) -> Iterator[tuple[pd.DataFrame, IngestionReport]]Read a CSV in chunks, yielding a typed frame and report per chunk.
This is the memory-aware counterpart to read_csv_safe. Each chunk is read as text, coerced under contract, and audited independently, so the peak memory stays close to chunksize rows instead of the whole file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | os.PathLike[str] | IO[Any] | Path or file-like object accepted by | required |
contract | DataContract | None | Optional | None |
chunksize | int | Number of rows per chunk. Must be a positive integer. | 100000 |
on_error | IngestionPolicy |
| 'warn' |
unique_tracking | Literal['memory', 'disk', 'auto'] | Storage for the values already seen in | 'auto' |
unique_tracking_limit | int | Number of tracked distinct values at which | 1000000 |
unique_tracking_path | str | os.PathLike[str] | None | Optional path for the SQLite database used by disk tracking. When omitted, a temporary directory is created and removed when the iterator is closed. | None |
**read_csv_kwargs | Any | Extra options passed to | required |
Yields:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, IngestionReport] | One typed frame and report per chunk. The report’s |
Notes:
ColumnSpec(unique=True) is checked within each chunk and against values seen in earlier chunks. Missing values are ignored. Cross-chunk tracking keeps one entry per distinct value in the unique columns, so its memory grows with cardinality rather than with the number of rows. Use combine_ingestion_reports to roll the per-chunk reports up.
data_cleaner.combine_ingestion_reports
combine_ingestion_reports(reports: Iterable[IngestionReport], *, source: str | None = None) -> IngestionReportRoll per-chunk reports into one report for a whole file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reports | Iterable[IngestionReport] | Reports yielded by | required |
source | str | None | Optional label for the combined report. Defaults to the source recorded on the first report. | None |
Returns:
| Type | Description |
|---|---|
IngestionReport | A report whose |
data_cleaner.read_excel_safe
read_excel_safe(source: str | os.PathLike[str] | IO[Any], contract: DataContract | None = None, *, sheet_name: str | int = 0, on_error: IngestionPolicy = 'warn', **read_excel_kwargs: Any) -> tuple[pd.DataFrame, IngestionReport]Read one Excel worksheet, coerce it under a contract, and audit it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | os.PathLike[str] | IO[Any] | Path or file-like object accepted by | required |
contract | DataContract | None | Optional | None |
sheet_name | str | int | Worksheet to read, either a name or a non-negative zero-based index. The default is the first sheet. The resolved sheet name is recorded on the report. | 0 |
on_error | IngestionPolicy |
| 'warn' |
**read_excel_kwargs | Any | Extra options passed to | required |
Returns:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, IngestionReport] | The typed frame and an audit report. String columns are kept as |
Notes:
Excel cells carry native types. The reader keeps those types long enough to detect identifiers stored as numbers, then applies the same identifier, date, numeric, and boolean guards as read_csv_safe. Real date cells are parsed directly; numeric serials in a datetime column are parsed as dates and flagged with excel_serial_date.
An identifier cell that Excel stored as a number has already lost any leading zeros. The report emits a numeric_identifier warning when a contract declares such a column as an ID. Store identifiers as text in the workbook to preserve them.
The excel extra installs openpyxl for .xlsx and .xlsm files. Legacy .xls, .xlsb, and .ods files need the matching optional pandas engine (xlrd, pyxlsb, or odfpy).
data_cleaner.read_parquet_safe
read_parquet_safe(source: str | os.PathLike[str] | IO[Any], contract: DataContract | None = None, *, on_error: IngestionPolicy = 'warn', **read_parquet_kwargs: Any) -> tuple[pd.DataFrame, IngestionReport]Read a Parquet file, coerce it under a contract, and audit it.
Requires PyArrow, installed with the parquet extra:
`bash pip install "universal-data-cleaner[parquet]" `
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | os.PathLike[str] | IO[Any] | Path or file-like object accepted by | required |
contract | DataContract | None | Optional | None |
on_error | IngestionPolicy |
| 'warn' |
**read_parquet_kwargs | Any | Extra options passed to | required |
Returns:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, IngestionReport] | The audited frame and its report. |
Notes:
Parquet already carries column types, but this reader applies the same contract-driven audit as read_csv_safe so ingestion reports are comparable across formats. Numeric columns are normalized to float64 during that audit, exactly like CSV input; the cleaner preserves integer dtypes again where it can. Identifiers stored as numbers in Parquet have already lost their leading zeros, so store identifiers as text at write time.
This function reads the whole file into memory. For large files, use iter_parquet_safe, which streams record batches.
data_cleaner.iter_parquet_safe
iter_parquet_safe(source: str | os.PathLike[str] | IO[Any], contract: DataContract | None = None, *, batch_size: int = 100000, on_error: IngestionPolicy = 'warn', unique_tracking: Literal['memory', 'disk', 'auto'] = 'auto', unique_tracking_limit: int = 1000000, unique_tracking_path: str | os.PathLike[str] | None = None, **read_parquet_kwargs: Any) -> Iterator[tuple[pd.DataFrame, IngestionReport]]Stream a Parquet file as audited batches.
Requires PyArrow. This is the memory-aware counterpart to read_parquet_safe: it reads one record batch at a time, so peak memory tracks batch_size rather than the whole file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | os.PathLike[str] | IO[Any] | Path or seekable file-like object accepted by | required |
contract | DataContract | None | Optional | None |
batch_size | int | Rows per batch. Must be a positive integer. | 100000 |
on_error | IngestionPolicy |
| 'warn' |
unique_tracking | Literal['memory', 'disk', 'auto'] | Same semantics as | 'auto' |
unique_tracking_limit | int | Same semantics as | 1000000 |
unique_tracking_path | str | os.PathLike[str] | None | Same semantics as | None |
**read_parquet_kwargs | Any | Extra options accepted by | required |
Yields:
| Type | Description |
|---|---|
tuple[pandas.DataFrame, IngestionReport] | One audited batch and its report. Batch indexes are continuous across the file, so concatenating the frames preserves row order. |
data_cleaner.CleanerReportdataclass
A single review object for one DataFrame, CSV, or Excel batch.
The report combines the dataset profile with contract findings, validation results, ingestion findings, and (when available) the cleaner’s decision log. It never mutates the input frame and never transforms it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Human-readable label for the batch, usually a file name. | required |
overview | dict[str, object] | Dataset-level metrics from | required |
profile | pd.DataFrame | Column-level profile from | required |
drift | DriftReport | None | Contract findings for the batch, when a contract is available. | None |
validation | ValidationReport | None | Expectation results, when expectations are supplied. | None |
ingestion | IngestionReport | None | CSV or Excel ingestion findings, when the batch came from | None |
decisions | pd.DataFrame | The fitted cleaner’s decision log, when auditing with a cleaner. | <factory> |
high_missing_threshold | float | None | Missing-percentage at which the profile emits a | 50.0 |
library_version | str | Version of Universal Data Cleaner that produced the report. | '2.12.0' |
from_frame
from_frame(frame: pd.DataFrame, *, source: str = 'dataset', name: str = 'dataset', contract: DataContract | None = None, expectations: Expectation | Sequence[Expectation] | None = None, ingestion: IngestionReport | None = None, decisions: pd.DataFrame | None = None, include_profile: bool = True, high_missing_threshold: float | None = 50.0) -> CleanerReportBuild a report for an in-memory DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame | pd.DataFrame | The batch to inspect. It is never modified. | required |
source | str | Label recorded in the report. | 'dataset' |
name | str | Dataset name used in the column profile. | 'dataset' |
contract | DataContract | None | Optional contract. When provided, its findings become the report’s contract section. | None |
expectations | Expectation | Sequence[Expectation] | None | Optional expectation or sequence of expectations to evaluate. | None |
ingestion | IngestionReport | None | Optional ingestion report to attach, for example from | None |
decisions | pd.DataFrame | None | Optional decision log to attach, for example from a fitted cleaner. | None |
include_profile | bool | Compute the column-level profile. Disable it for very large batches when only findings are needed. | True |
high_missing_threshold | float | None | Missing-percentage threshold for a | 50.0 |
from_csv
from_csv(source: str | os.PathLike[str] | IO[Any], *, contract: DataContract | None = None, expectations: Expectation | Sequence[Expectation] | None = None, name: str | None = None, include_profile: bool = True, high_missing_threshold: float | None = 50.0, on_error: IngestionPolicy = 'ignore', **read_csv_kwargs: Any) -> CleanerReportRead a CSV with read_csv_safe and audit the result.
The default on_error="ignore" always returns a report; error findings still make success false. Pass "raise" to stop at the first unparseable value instead.
from_excel
from_excel(source: str | os.PathLike[str] | IO[Any], *, sheet_name: str | int = 0, contract: DataContract | None = None, expectations: Expectation | Sequence[Expectation] | None = None, name: str | None = None, include_profile: bool = True, high_missing_threshold: float | None = 50.0, on_error: IngestionPolicy = 'ignore', **read_excel_kwargs: Any) -> CleanerReportRead one Excel worksheet with read_excel_safe and audit it.
The default on_error="ignore" always returns a report; error findings still make success false. Pass "raise" to stop at the first unparseable value instead. Excel support requires the excel extra (openpyxl for .xlsx and .xlsm).
from_cleaner
from_cleaner(cleaner: Any, frame: pd.DataFrame, *, source: str = 'batch', name: str = 'batch', expectations: Expectation | Sequence[Expectation] | None = None, ingestion: IngestionReport | None = None, include_profile: bool = True, high_missing_threshold: float | None = 50.0) -> CleanerReportAudit a batch against a fitted DataCleaner.
The cleaner’s fitted contract supplies the drift section and its decision log is attached to the report. The cleaner is not re-fitted and the batch is not transformed.
findings
A tidy table of every error and warning in the report.
errors
Findings with error severity.
warnings
Findings with warning severity.
has_errors
Whether at least one error-severity finding exists.
has_warnings
Whether at least one warning-severity finding exists.
success
Whether the batch has no error-severity findings.
summary
summary() -> strReturn a short human-readable description of the report.
to_markdown
to_markdown() -> strRender the whole report as Markdown.
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the report.
to_json
to_json(**kwargs: object) -> strSerialize the report to JSON.
raise_if_failed
raise_if_failed(message: str = 'Batch audit failed') -> NoneRaise ValueError when any error-severity finding exists.
data_cleaner.Expectationdataclass
A single, reusable data expectation.
Prefer the factory functions (not_null, unique, in_set, between, matches_pattern, has_dtype, row_count_between) over constructing this class directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | required | |
column | str | None | None | |
values | tuple[object, ...] | None | None | |
lower | float | None | None | |
upper | float | None | None | |
inclusive | bool | True | |
pattern | str | None | None | |
dtype | str | None | None | |
min_rows | int | None | None | |
max_rows | int | None | None | |
severity | Severity | 'error' |
check
check(frame: pd.DataFrame) -> ValidationResultEvaluate this expectation against frame.
failing_mask
failing_mask(frame: pd.DataFrame) -> pd.Series | NoneReturn a boolean row mask for failing rows, when it is well-defined.
None means the expectation is frame-level (row count or dtype) or references a missing column, so row diagnostics cannot attribute the failure to individual rows.
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the expectation.
data_cleaner.ValidationResultdataclass
Outcome of a single expectation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expectation | str | required | |
column | str | None | required | |
success | bool | required | |
severity | Severity | required | |
message | str | required | |
observed | object | None |
to_dict
to_dict() -> dict[str, object]Return a tabular representation of the result.
data_cleaner.ValidationReportdataclass
Container for expectation results or contract findings.
sources keeps the evaluated expectations and rules so diagnose can attribute failures to rows. Reports built from contract findings have no sources and therefore produce an empty sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results | pd.DataFrame | required | |
source | str | 'expectations' | |
sources | tuple[Validatable, ...] | () |
from_results
from_results(results: Sequence[ValidationResult], *, sources: tuple[Validatable, ...] = ()) -> ValidationReportBuild a report from individual results.
from_findings
from_findings(findings: pd.DataFrame) -> ValidationReportBuild a report from DriftReport findings.
success
Whether every error-severity expectation passed.
failures
Rows for every failed expectation, including warnings.
has_warnings
Whether any warning-severity expectation failed.
summary
summary() -> strReturn a short human-readable description of the failures.
to_markdown
to_markdown() -> strRender the report as Markdown (falls back to plain text).
raise_if_failed
raise_if_failed(message: str = 'Validation failed') -> NoneRaise ValueError when an error-severity expectation failed.
diagnose
diagnose(frame: pd.DataFrame, *, limit: int = 5, include_values: bool = False, include_index: bool = True, max_value_length: int = 32) -> RowDiagnosticsSample a bounded set of failing rows for this report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame | pd.DataFrame | The frame the report was produced from. It is never modified. | required |
limit | int | Maximum sampled rows per failing expectation or rule. | 5 |
include_values | bool | Include the failing value for rules that target a single column. Values are off by default because they may contain personal data. | False |
include_index | bool | Include the frame index label for sampled rows. Labels are off by default when the index may contain identifiers; set this to | True |
max_value_length | int | Truncate included values to this many characters. | 32 |
Returns:
| Type | Description |
|---|---|
RowDiagnostics | Sampled rows, whether any sample was truncated, and the rules that could not be attributed to rows. |
data_cleaner.validate
validate(frame: pd.DataFrame, expectations: Validatable | Sequence[Validatable]) -> ValidationReportEvaluate one or more expectations or rules against frame.
Warning-severity failures are reported but do not make the report fail. Custom objects that implement Validatable are accepted, and a rule may return several results from one check call.
data_cleaner.not_null
not_null(column: str, *, severity: Severity = 'error') -> ExpectationExpect column to contain no missing values.
data_cleaner.unique
unique(column: str, *, severity: Severity = 'error') -> ExpectationExpect non-null values in column to be unique.
data_cleaner.in_set
in_set(column: str, values: Sequence[object], *, severity: Severity = 'error') -> ExpectationExpect non-null values in column to belong to values.
data_cleaner.between
between(column: str, lower: float | None = None, upper: float | None = None, *, inclusive: bool = True, severity: Severity = 'error') -> ExpectationExpect numeric values in column to fall within the given bounds.
data_cleaner.matches_pattern
matches_pattern(column: str, pattern: str, *, severity: Severity = 'error') -> ExpectationExpect non-null string values in column to fully match pattern.
data_cleaner.has_dtype
has_dtype(column: str, dtype: str, *, severity: Severity = 'error') -> ExpectationExpect column to have a broad kind or an exact pandas dtype.
Broad kinds are numeric, categorical, boolean, and datetime. Exact pandas dtypes such as float64 or datetime64[ns] are compared directly.
data_cleaner.row_count_between
row_count_between(min_rows: int | None = None, max_rows: int | None = None, *, severity: Severity = 'error') -> ExpectationExpect the frame to have between min_rows and max_rows rows.
data_cleaner.Validatable
Anything validate can evaluate.
The built-in Expectation and the composable rules in rules implement this protocol. A custom object only needs name, column, severity, and check(frame); check may return one ValidationResult or a list of them.
name
column
severity
check
check(frame: pd.DataFrame) -> ValidationResult | list[ValidationResult]data_cleaner.Condition
A boolean row predicate over one or more columns.
mask
mask(frame: pd.DataFrame) -> pd.SeriesReturn a boolean mask aligned with frame.
known
known(frame: pd.DataFrame) -> pd.SeriesReturn rows where the condition can be evaluated.
Comparisons drop rows where either operand is missing. Those rows are not treated as failures, so a rule does not flag missing data unless the rule explicitly uses col(...).isna().
describe
describe() -> strReturn a short, stable human-readable description.
columns
columns() -> tuple[str, ...]Return the columns the condition reads.
require
require(*, name: str | None = None, severity: Severity = 'error') -> PredicateRuleTurn this condition into a row-level rule.
data_cleaner.ColumnRef
A reference to a column inside a Condition.
eq
eq(other: object) -> ConditionRequire equality with a value or another column.
ne
ne(other: object) -> ConditionRequire inequality with a value or another column.
lt
lt(other: object) -> ConditionRequire a value strictly less than other.
le
le(other: object) -> ConditionRequire a value less than or equal to other.
gt
gt(other: object) -> ConditionRequire a value strictly greater than other.
ge
ge(other: object) -> ConditionRequire a value greater than or equal to other.
isin
isin(values: Sequence[object]) -> ConditionRequire membership in values.
not_in
not_in(values: Sequence[object]) -> ConditionRequire non-membership in values.
between
between(lower: object | None = None, upper: object | None = None, *, inclusive: bool = True) -> ConditionRequire a value within the given bounds.
isna
isna() -> ConditionRequire a missing value.
notna
notna() -> ConditionRequire a present value.
matches
matches(pattern: str) -> ConditionRequire a full-string regular-expression match.
data_cleaner.col
col(name: str) -> ColumnRefStart a condition from a column reference.
data_cleaner.row_rule
row_rule(condition: Condition, *, name: str | None = None, severity: Severity = 'error') -> PredicateRuleRequire every row to satisfy condition.
Comparisons drop rows where either side is missing, so a missing value does not fail a predicate unless the predicate explicitly asks for it with col(...).isna().
data_cleaner.PredicateRuledataclass
A row-level rule: every row must satisfy condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition | Condition | required | |
name | str | required | |
severity | Severity | 'error' | |
column | str | None | None |
value_column
The single column a failing value can be read from, if any.
check
check(frame: pd.DataFrame) -> ValidationResultfailing_mask
failing_mask(frame: pd.DataFrame) -> pd.Series | Nonedata_cleaner.conditional
conditional(condition: Condition, rule: Validatable, *, name: str | None = None, severity: Severity | None = None) -> ConditionalRuleApply rule only to rows where condition holds.
Rows outside the condition are not evaluated. If no row matches, the rule passes and reports that nothing was checked.
data_cleaner.ConditionalRuledataclass
Apply a rule only to rows where condition holds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition | Condition | required | |
rule | Validatable | required | |
name | str | required | |
severity | Severity | 'error' | |
column | str | None | None |
value_column
The single column the inner rule reports a value for, if any.
check
check(frame: pd.DataFrame) -> ValidationResultfailing_mask
failing_mask(frame: pd.DataFrame) -> pd.Series | Nonedata_cleaner.grouped
grouped(by: str | Sequence[str], rule: Validatable, *, name: str | None = None, severity: Severity | None = None, max_groups: int = 10, include_groups: bool = False) -> GroupedRuleApply rule independently inside each group.
The result reports how many groups failed. Group labels are omitted by default because they can contain personal data; pass include_groups=True to list up to max_groups failing labels.
data_cleaner.GroupedRuledataclass
Apply a rule independently inside each group of by.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by | tuple[str, ...] | required | |
rule | Validatable | required | |
name | str | required | |
severity | Severity | 'error' | |
column | str | None | None | |
max_groups | int | 10 | |
include_groups | bool | False |
value_column
Grouped findings cannot be attributed to a single value.
check
check(frame: pd.DataFrame) -> ValidationResultfailing_mask
failing_mask(frame: pd.DataFrame) -> pd.Series | Nonedata_cleaner.unique_combination
unique_combination(columns: Sequence[str], *, name: str | None = None, severity: Severity = 'error') -> UniqueCombinationRuleRequire the combination of columns to be unique.
Rows where any key is missing are ignored, matching unique for a single column.
data_cleaner.UniqueCombinationRuledataclass
Require the combination of columns to be unique.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns | tuple[str, ...] | required | |
name | str | 'unique_combination' | |
severity | Severity | 'error' | |
column | str | None | None |
value_column
Only a single-column rule has a value to show.
check
check(frame: pd.DataFrame) -> ValidationResultfailing_mask
failing_mask(frame: pd.DataFrame) -> pd.Series | Nonedata_cleaner.sum_equals
sum_equals(columns: Sequence[str], target: str, *, tolerance: float = 1e-09, name: str | None = None, severity: Severity = 'error') -> SumEqualsRuleRequire the numeric sum of columns to equal target per row.
data_cleaner.SumEqualsRuledataclass
Require the sum of columns to equal target within tolerance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns | tuple[str, ...] | required | |
target | str | required | |
tolerance | float | required | |
name | str | 'sum_equals' | |
severity | Severity | 'error' | |
column | str | None | None |
value_column
The target column is the value to show when a row fails.
check
check(frame: pd.DataFrame) -> ValidationResultfailing_mask
failing_mask(frame: pd.DataFrame) -> pd.Series | Nonedata_cleaner.RowDiagnosticsdataclass
A bounded, privacy-safe sample of failing rows.
rows has one record per sampled failure with the expectation name, the column, the positional row number, and the index label. Values are excluded by default; when ValidationReport.diagnose is called with include_values=True they are truncated to max_value_length characters. truncated is true when at least one rule had more failing rows than the sampling limit. skipped lists rules whose failures cannot be attributed to individual rows, such as frame-level row-count checks or grouped rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows | pd.DataFrame | required | |
truncated | bool | False | |
skipped | tuple[str, ...] | () |
empty
Whether no rows were sampled.
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the sample.
to_markdown
to_markdown() -> strRender the sample as Markdown.
data_cleaner.DriftPolicydataclass
Thresholds and sampling controls for a distribution comparison.
PSI follows the conventional interpretation: below psi_warning the distributions are considered stable, at or above psi_warning the shift is moderate, and at or above psi_error it is major. Missingness and category deltas are expressed in percentage points. Wasserstein thresholds apply to a scale-free ratio (distance divided by the reference standard deviation, or by the value range when the deviation is zero), so the same policy works across columns with different units.
min_sample downgrades an error-severity finding to a warning when either side has fewer than that many rows, because small samples make every metric unstable. Set it to 0 to disable the downgrade.
Thresholds must be finite and non-negative, with each error threshold greater than or equal to its warning threshold. Counts must be integers. Values are normalized when the policy is created, so NumPy integers round-trip cleanly through JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psi_warning | float | None | 0.1 | |
psi_error | float | None | 0.25 | |
wasserstein_warning | float | None | None | |
wasserstein_error | float | None | None | |
missing_delta_warning | float | None | 5.0 | |
missing_delta_error | float | None | None | |
category_delta_warning | float | None | 10.0 | |
category_delta_error | float | None | None | |
min_sample | int | 20 | |
bins | int | 10 | |
max_categories | int | 20 | |
max_columns | int | 200 | |
wasserstein_points | int | 512 |
to_dict
to_dict() -> dict[str, object]Return a JSON-serializable representation of the policy.
from_dict
from_dict(data: dict[str, object]) -> DriftPolicyRebuild a policy from to_dict output.
to_json
to_json(**kwargs: object) -> strSerialize the policy to JSON.
from_json
from_json(text: str) -> DriftPolicyParse a policy from JSON.
data_cleaner.DriftProfiledataclass
A compact reference summary for distribution comparisons.
Build it once from a reference (training) frame and reuse it for every batch. Numeric columns keep quantile bin edges and a bounded quantile sample used for the Wasserstein distance; categorical columns keep the most common levels plus an other bucket. Everything is JSON-serializable, so a profile survives a round trip through a report sink.
The profile is a derived summary, not a copy of the reference rows. It still contains quantile values and retained category labels, so treat it as you would treat a schema and avoid logging it. The default repr is redacted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns | dict[str, _ColumnProfile] | required | |
policy | DriftPolicy | required | |
rows | int | required | |
skipped_columns | tuple[str, ...] | () |
from_frame
from_frame(frame: pd.DataFrame, *, columns: list[str] | tuple[str, ...] | None = None, policy: DriftPolicy | None = None) -> DriftProfileProfile a reference frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame | pd.DataFrame | Reference data. It is never modified. | required |
columns | list[str] | tuple[str, ...] | None | Columns to profile. When omitted, every numeric, categorical, boolean, and datetime column is profiled, up to | None |
policy | DriftPolicy | None | Thresholds and sampling controls stored with the profile. | None |
Raises:
| Type | Description |
|---|---|
ValueError | If the frame is empty or no comparable columns are available. |
KeyError | If an explicitly requested column is missing. |
compare
compare(frame: pd.DataFrame, *, policy: DriftPolicy | None = None) -> DistributionDriftReportCompare frame against this reference profile.
The reference columns decide what is compared. Columns present only in frame are ignored; reference columns missing from frame are reported as structural errors.
to_dict
to_dict() -> dict[str, object]Return a JSON-safe representation of the profile.
from_dict
from_dict(data: dict[str, object]) -> DriftProfileRebuild a profile from to_dict output.
to_json
to_json(**kwargs: object) -> strSerialize the profile to JSON.
from_json
from_json(text: str) -> DriftProfileParse a profile from JSON.
data_cleaner.DistributionDriftReportdataclass
Reference-versus-current statistical drift for a set of columns.
columns holds one row per compared column with PSI, Wasserstein distance, its scale-free ratio, missingness deltas, and the largest category delta. categories holds the bounded per-category detail for categorical columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns | pd.DataFrame | required | |
categories | pd.DataFrame | required | |
reference_rows | int | required | |
current_rows | int | required | |
policy | DriftPolicy | required | |
reference | DriftProfile | None | None |
has_drift
Whether any column left the stable band.
drifted_columns
Names of columns whose status is not stable.
errors
Column-level findings with error severity.
warnings
Column-level findings with warning severity.
has_errors
Whether at least one column has an error-severity finding.
has_warnings
Whether at least one column has a warning-severity finding.
summary
summary() -> strReturn a short human-readable description of the drift.
to_markdown
to_markdown() -> strRender the comparison as Markdown.
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the report.
to_json
to_json(**kwargs: object) -> strSerialize the report to JSON.
raise_if_drift
raise_if_drift(message: str = 'Statistical drift detected') -> NoneRaise ValueError when an error-severity finding exists.
data_cleaner.compare_distributions
compare_distributions(reference: pd.DataFrame, current: pd.DataFrame, *, columns: list[str] | tuple[str, ...] | None = None, policy: DriftPolicy | None = None) -> DistributionDriftReportCompare the distributions of reference and current.
This is a convenience wrapper around DriftProfile.from_frame and DriftProfile.compare. Use the profile directly when the same reference is compared with many batches.
data_cleaner.JsonlReportSink
Append reports to a JSON Lines file and read the batch history back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | os.PathLike[str] | Destination file. It is created on first write. | required |
create_parents | bool | Create missing parent directories when the sink is constructed. | True |
fsync | bool | Flush each appended record to disk before returning. Off by default because it trades throughput for crash durability. When enabled, the parent directory is also synced the first time a file is created so the new entry itself is durable. | False |
write
write(report: CleanerReport | DistributionDriftReport | Mapping[str, Any], *, recorded_at: datetime | str | None = None, metadata: Mapping[str, Any] | None = None, source: str | None = None) -> dict[str, object]Append one report and return the stored record.
Each record is a single line. The sink does not lock the file, so give each concurrent writer its own file or serialize writes externally.
read
read() -> list[dict[str, object]]Read every stored record, in append order.
history
history() -> pd.DataFrameReturn a one-row-per-batch summary of the stored records.
latest
latest(*, kind: str | None = None, source: str | None = None) -> dict[str, object] | NoneReturn the most recently appended matching record, or None.
drift_against_previous
drift_against_previous(frame: pd.DataFrame, *, policy: DriftPolicy | None = None, source: str | None = None) -> DistributionDriftReportCompare frame with the reference profile of the latest drift report.
The recorded policy is reused when policy is omitted, so a historical comparison is reproducible with the thresholds that were in force when the reference report was written.
data_cleaner.JoinDiagnosisdataclass
Findings from a join cardinality and row-preservation check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
how | str | required | |
on | tuple[str, ...] | required | |
validate | str | None | required | |
left_rows | int | required | |
right_rows | int | required | |
output_rows | int | required | |
row_multiplier | float | required | |
left_cardinality | str | required | |
right_cardinality | str | required | |
cardinality | str | required | |
cardinality_matches | bool | required | |
left_duplicate_keys | int | required | |
right_duplicate_keys | int | required | |
left_duplicate_rows | int | required | |
right_duplicate_rows | int | required | |
left_null_keys | int | required | |
right_null_keys | int | required | |
unmatched_left | int | required | |
unmatched_right | int | required | |
safe | bool | required | |
warnings | tuple[str, ...] | required |
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the diagnosis.
to_markdown
to_markdown() -> strRender the diagnosis as a Markdown table.
raise_if_unsafe
raise_if_unsafe(message: str = 'Join is not safe') -> NoneRaise ValueError when the diagnosis is not safe.
data_cleaner.diagnose_join
diagnose_join(left: pd.DataFrame, right: pd.DataFrame, on: str | Sequence[str], how: JoinHow = 'left', validate: JoinCardinality | None = '1:1') -> JoinDiagnosisDiagnose key duplication, cardinality, and row preservation for a join.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left | pd.DataFrame | Frames to join. Only key columns are inspected. | required |
right | pd.DataFrame | Frames to join. Only key columns are inspected. | required |
on | str | Sequence[str] | Key column name or names. Both frames must contain every key. | required |
how | JoinHow | One of | 'left' |
validate | JoinCardinality | None | Expected maximum cardinality: | '1:1' |
Notes:
row_multiplier is output_rows / len(left) and is 0.0 when the left frame is empty. safe is false when the join violates the requested cardinality, multiplies rows on the preserved side of a left/right join, or has null keys.
data_cleaner.ReferentialIntegrityReportdataclass
Findings from a child-to-parent key integrity check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
child_key | tuple[str, ...] | required | |
parent_key | tuple[str, ...] | required | |
child_rows | int | required | |
parent_rows | int | required | |
matched_rows | int | required | |
orphan_rows | int | required | |
orphan_key_count | int | required | |
orphan_keys | tuple[tuple[object, ...], ...] | required | |
null_child_keys | int | required | |
null_parent_keys | int | required | |
parent_duplicate_keys | int | required | |
valid | bool | required | |
warnings | tuple[str, ...] | required |
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the report.
to_markdown
to_markdown() -> strRender the report as a Markdown table.
raise_if_invalid
raise_if_invalid(message: str = 'Referential integrity check failed') -> NoneRaise ValueError when the relationship is not valid.
data_cleaner.check_referential_integrity
check_referential_integrity(child: pd.DataFrame, parent: pd.DataFrame, child_key: str | Sequence[str], parent_key: str | Sequence[str] | None = None, *, allow_null_keys: bool = True) -> ReferentialIntegrityReportCheck that every non-null child key exists in the parent table.
parent_key defaults to child_key. Null child keys are reported separately and are allowed by default; set allow_null_keys=False to make them invalid. Duplicate parent keys make the relationship invalid because the parent key is not a unique reference target. orphan_keys contains up to 10 distinct examples; orphan_key_count is the total.
data_cleaner.DeduplicationReportdataclass
Audit trail for deduplicate_by_business_key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key | tuple[str, ...] | required | |
keep | str | required | |
tie_breaker | tuple[str, ...] | None | required | |
input_rows | int | required | |
output_rows | int | required | |
removed_rows | int | required | |
duplicate_keys | int | required | |
null_key_rows | int | required | |
removed | pd.DataFrame | required | |
warnings | tuple[str, ...] | required |
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly summary (without the removed rows).
to_markdown
to_markdown() -> strRender the report as a Markdown table.
data_cleaner.deduplicate_by_business_key
deduplicate_by_business_key(frame: pd.DataFrame, key: str | Sequence[str], keep: Keep = 'first', tie_breaker: str | Sequence[str] | None = None) -> tuple[pd.DataFrame, DeduplicationReport]Deduplicate rows by a business key and report what was removed.
keep selects the first or last row per key. tie_breaker sorts rows within each key before selecting and prefers non-null values. The returned frame preserves the input row order and index, and the input is never mutated.
data_cleaner.SplitAuditdataclass
Findings from audit_split.
findings is a tidy DataFrame with check, column, severity, message, train, and test columns. The report only describes problems; it never modifies the data or repairs a split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
findings | pd.DataFrame | required | |
train_rows | int | required | |
test_rows | int | required | |
task | ResolvedTask | None | required | |
duplicate_overlap_rows | int | 0 | |
near_duplicate_overlap_rows | int | 0 | |
group_overlap | int | 0 | |
time_overlap_rows | int | 0 |
valid
Whether the audit found no error-severity issues.
errors
Findings with error severity.
warnings
Findings with warning severity.
has_errors
Whether at least one error-severity finding exists.
has_warnings
Whether at least one warning-severity finding exists.
summary
summary() -> strReturn a short human-readable description of the findings.
to_markdown
to_markdown() -> strRender the findings as a Markdown table (falls back to text).
to_dict
to_dict() -> dict[str, object]Return a JSON-friendly representation of the audit.
raise_if_invalid
raise_if_invalid(message: str = 'Split audit failed') -> NoneRaise ValueError when at least one error-severity finding exists.
data_cleaner.audit_split
audit_split(X_train: pd.DataFrame, X_test: pd.DataFrame, y_train: Sequence[object] | pd.Series | np.ndarray | None = None, y_test: Sequence[object] | pd.Series | np.ndarray | None = None, *, groups: Sequence[object] | pd.Series | np.ndarray | None = None, groups_test: Sequence[object] | pd.Series | np.ndarray | None = None, time_col: str | None = None, id_cols: str | Sequence[str] | None = None, task: TaskType = 'auto', near_duplicate_decimals: int | None = 3, constant_threshold: float = 0.99, high_cardinality_threshold: float = 0.9, high_cardinality_min_unique: int = 20, missingness_shift_threshold: float = 0.1, distribution_shift_threshold: float = 0.5, categorical_shift_threshold: float = 0.2, target_correlation_threshold: float = 0.95, target_nmi_threshold: float = 0.9, target_shift_threshold: float = 0.5, classification_max_classes: int = 20, max_target_leak_categories: int = 50) -> SplitAuditAudit a train/test split for leakage and distribution problems.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train | pd.DataFrame | Feature frames. They are never modified. | required |
X_test | pd.DataFrame | Feature frames. They are never modified. | required |
y_train | Sequence[object] | pd.Series | np.ndarray | None | Optional targets, aligned by position. Both must be supplied together. | None |
y_test | Sequence[object] | pd.Series | np.ndarray | None | Optional targets, aligned by position. Both must be supplied together. | None |
groups | Sequence[object] | pd.Series | np.ndarray | None | Group labels for the training rows. If | None |
groups_test | Sequence[object] | pd.Series | np.ndarray | None | Group labels for the test rows when | None |
time_col | str | None | Optional timestamp column (datetime or text). When supplied, the audit treats the split as temporal and reports train timestamps at or after the earliest test timestamp. Numeric timestamp columns are rejected as ambiguous. | None |
id_cols | str | Sequence[str] | None | Optional identifier columns. They are excluded from duplicate, constant, distribution, and target-leakage checks. Declared identifiers are still reported under | None |
task | TaskType |
| 'auto' |
near_duplicate_decimals | int | None | Decimal places used to round numeric features before near-duplicate detection. | 3 |
constant_threshold | float | Share of the most frequent value at or above which a column is near-constant. | 0.99 |
high_cardinality_threshold | float | Unique-value share at or above which a column is high-cardinality. | 0.9 |
high_cardinality_min_unique | int | Minimum number of unique values before a column is called high-cardinality. | 20 |
missingness_shift_threshold | float | Absolute missing-rate change at or above which a finding is emitted. | 0.1 |
distribution_shift_threshold | float | Standardized mean difference at or above which a numeric feature is reported as shifted. | 0.5 |
categorical_shift_threshold | float | Total variation distance at or above which a categorical feature is reported as shifted. | 0.2 |
target_correlation_threshold | float | Absolute correlation at or above which a numeric feature is suspected of target leakage. | 0.95 |
target_nmi_threshold | float | Normalized mutual information at or above which a categorical feature is suspected of target leakage. | 0.9 |
target_shift_threshold | float | Target-distribution shift threshold. Used as total variation distance for classification and standardized mean difference for regression. | 0.5 |
classification_max_classes | int | Maximum unique integer target values inferred as classification when | 20 |
max_target_leak_categories | int | Maximum feature cardinality considered for the categorical target-leakage heuristic. | 50 |
Returns:
| Type | Description |
|---|---|
SplitAudit | A severity-tagged findings table plus convenience properties and |
Notes:
Schema problems (missing columns), empty splits, exact duplicate overlap, group leakage, temporal leakage, and unparseable or numeric timestamps are errors. Statistical and heuristic checks (near-duplicates, constants, cardinality, missingness, distribution shift, target leakage, and target shift) are warnings because they can be legitimate dataset properties.
Duplicate checks exclude id_cols and time_col. Near-duplicates are approximated by hashing rows with numeric features rounded to near_duplicate_decimals; this is deterministic and dependency-light, not an exact nearest-neighbour search.
Findings never include raw cell values. Messages carry column names, counts, rates, and statistics only.
Numeric target-leakage correlation covers regression and binary classification. Multiclass targets use normalized mutual information, which only evaluates features with limited cardinality; a continuous feature that perfectly encodes a multiclass target may not be flagged.
data_cleaner.ArtifactCompatibilityError
Bases: RuntimeError
Raised when a saved artifact cannot be loaded by this library version.
data_cleaner.fingerprint_dataframe
fingerprint_dataframe(frame: pd.DataFrame, columns: Sequence[str] | None = None) -> strReturn a stable SHA-256 fingerprint of a frame’s schema and summary stats.
The hash deliberately excludes raw values: it is a lineage fingerprint, not a row-level checksum. Column order participates in the hash, and summary statistics are rounded so the result is stable across platforms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame | pd.DataFrame | DataFrame to fingerprint. | required |
columns | Sequence[str] | None | Optional subset/order of columns. Defaults to all columns in frame order. | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
KeyError | If a requested column is missing from |
data_cleaner.compare_fingerprints
compare_fingerprints(left: str, right: str) -> boolReturn True when two fingerprints are identical.
data_cleaner.assert_schema_stable
assert_schema_stable(frame: pd.DataFrame, expected: str, *, name: str = 'frame') -> NoneRaise ValueError when frame does not match expected.
expected is a fingerprint produced by fingerprint_dataframe.
data_cleaner.profile_dataframe
profile_dataframe(frame: pd.DataFrame, name: str = 'dataset') -> pd.DataFrameCreate a column-level data quality profile.
data_cleaner.dataset_summary
dataset_summary(frame: pd.DataFrame) -> dict[str, object]Return dataset-level quality metrics.
data_cleaner.drop_duplicate_rows
drop_duplicate_rows(frame: pd.DataFrame, subset: list[str] | None = None, keep: Literal['first', 'last'] = 'first') -> tuple[pd.DataFrame, int]Drop exact duplicates and return (deduplicated_frame, rows_removed).
data_cleaner.assert_frame_clean
assert_frame_clean(frame: pd.DataFrame, *, allow_empty: bool = True) -> NoneAssert that a cleaned frame has no missing/infinite values.
The package follows semantic versioning for its public API.
| Tier | What it covers | Guarantee |
|---|---|---|
| Stable | Every name in data_cleaner.__all__ | No breaking change in the 2.x line |
| Experimental | Names documented as experimental | May change in a minor release; keep usage isolated |
| Internal | Modules prefixed with _ and attributes ending in _ | Not part of the public API; do not import or rely on them |
data_cleaner.__all__ is the canonical public surface. If a name is not listed there, it is not supported for direct import. The current release has no experimental public names.
- A public name is deprecated with a
DeprecationWarningand a documented replacement. - Deprecated names remain available for at least one minor release.
- Removals happen only in a major release, with a changelog entry and a migration note.
- Additive changes (new optional parameters, new reports, new helpers) ship in a minor release and keep existing calls working.
- All public names are re-exported from the package root, so
from data_cleaner import ...is the supported import style. - Configuration objects are immutable dataclasses; create a new one when options change.
- Learned state lives on the fitted
DataCleaner, not on the input DataFrame. - Reports expose structured attributes plus
to_markdown()where available, so they can be logged or attached to a model review. - The generated signatures show the exact accepted types. The guides include complete, runnable examples for the common paths.