Skip to content
Start here

API reference

This page is generated from the package docstrings. Every public name is importable directly from data_cleaner.

Python
from data_cleaner import DataCleaner, audit_split, validate

ObjectUse it for
DataCleanerFit cleaning rules on training data and transform later batches
CleanerConfigConfigure imputation, outliers, datetime features, contracts, and drift policy
DataContractDeclare column roles, allowed values, ranges, patterns, and uniqueness
read_csv_safeRead CSV as text, coerce under a contract, and audit the conversion
iter_csv_safeStream a large CSV in typed chunks with one audit report per chunk
combine_ingestion_reportsRoll per-chunk ingestion reports into one whole-file report
read_excel_safeRead one Excel sheet with the same guards and audit report
read_parquet_safeRead Parquet under a contract with the same audit report (PyArrow extra)
iter_parquet_safeStream a large Parquet file in audited record batches
combine_drift_reportsRoll per-chunk drift reports into one run-level TransformReport
CleanerReportCombine profile, contract, validation, ingestion, and decisions for one batch
validateEvaluate reusable expectations and rules against a DataFrame
compare_distributionsCompare a batch against a reference distribution with PSI and Wasserstein distance
JsonlReportSinkKeep an append-only batch history and compare against a stored reference
audit_splitCheck 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) -> DataCleaner

Learn cleaning rules from training data.

transform

transform(X: pd.DataFrame) -> pd.DataFrame

Apply 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:

NameTypeDescriptionDefault
Xpd.DataFrame

Inference batch. It is never mutated and no rows are dropped.

required

Returns:

TypeDescription
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:

NameTypeDescriptionDefault
chunksIterable[pd.DataFrame]

Iterable of DataFrames, usually produced by iter_csv_safe or iter_parquet_safe. A bare DataFrame is rejected because iterating it would yield column names, not batches.

required

Yields:

TypeDescription
tuple[pandas.DataFrame, DriftReport]

The cleaned chunk and its findings. report.rows is the chunk size. Use combine_drift_reports to roll the reports up without keeping every frame.

Examples:

Python
>>> 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.DataFrame

Fit on X and return the cleaned training DataFrame.

get_feature_names_out

get_feature_names_out(input_features: list[str] | None = None) -> np.ndarray

Return cleaned output column names.

cleaning_summary

cleaning_summary() -> pd.DataFrame

Return a learned cleaning summary for auditing/debugging.

outlier_summary

outlier_summary() -> pd.DataFrame

Return outlier bounds learned for numeric columns.

drift_report

drift_report() -> pd.DataFrame

Return the column-contract drift findings seen at the last transform.

fitted_contract

fitted_contract() -> DataContract | None

Return the contract used by this fitted cleaner.

decision_log

decision_log() -> pd.DataFrame

Return one row per learned or configured cleaning decision.

fingerprint

fingerprint(X: pd.DataFrame) -> str

Return 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:

NameTypeDescriptionDefault
Xpd.DataFrame | None

Optional frame to fingerprint. When omitted and include_fingerprint is true, the fingerprint computed during fit is used (requires CleanerConfig(fingerprint_on_fit=True)).

None
include_fingerprintbool

Include a fingerprint_dataframe hash in the manifest.

False

Raises:

TypeDescription
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) -> Path

Persist 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) -> DataCleaner

Load 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:

NameTypeDescriptionDefault
numeric_imputationLiteral['median', 'mean', 'constant']'median'
categorical_imputationLiteral['mode', 'constant']'mode'
numeric_fill_valuefloat0.0
categorical_fill_valuestr'Unknown'
cap_outliersboolFalse
outlier_multiplierfloat1.5
outlier_columnstuple[str, ...]()
add_missing_indicatorsboolFalse
drop_constant_columnsboolTrue
numeric_columnstuple[str, ...]()
categorical_columnstuple[str, ...]()
datetime_columnstuple[str, ...]()
datetime_featurestuple[str, ...]('year', 'month', 'day', 'dayofweek', 'is_weekend')
unseen_categoryLiteral['keep', 'fill']'keep'
preserve_integer_dtypesboolTrue
on_precision_lossLiteral['raise', 'warn', 'coerce']'coerce'
contractDataContract | NoneNone
on_driftLiteral['raise', 'warn', 'ignore']'warn'
infer_contractboolTrue
fingerprint_on_fitboolFalse
verboseboolTrue

data_cleaner.CleaningDecisiondataclass

A single auditable cleaning decision.

Parameters:

NameTypeDescriptionDefault
columnstr

Source column the decision applies to, or "*" for frame-level decisions such as contract inference.

required
actionstr

Short, machine-readable verb, for example "impute", "cap_outliers", "expand_datetime" or "drop_column".

required
reasonstr

Human-readable explanation of why the action was taken.

required
sourcestr

Where the rule came from: "learned" (learned from training data), "config" (explicit CleanerConfig), "contract" (column contract) or "default" (library default/inference).

required
beforeobject

Optional description of the state before the decision.

None
afterobject

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:

NameTypeDescriptionDefault
namestrrequired
rolestr | NoneNone
dtypestr | NoneNone
nullableboolTrue
uniqueboolFalse
allowed_valuestuple[object, ...] | NoneNone
min_valuefloat | NoneNone
max_valuefloat | NoneNone
patternstr | NoneNone
date_formatstr | NoneNone
preserve_leading_zerosboolFalse
severityLiteral['error', 'warning']'error'
requiredboolTrue

to_dict

to_dict() -> dict[str, object]

Return a JSON-serializable representation of the spec.

from_dict

from_dict(data: dict[str, object]) -> ColumnSpec

Rebuild 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:

NameTypeDescriptionDefault
columnstuple[ColumnSpec, ...]()
strictboolFalse

spec_for

spec_for(name: str) -> ColumnSpec | None

Return 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) -> DataContract

Infer a conservative contract from a training frame.

from_frame

from_frame(frame: pd.DataFrame, config: CleanerConfig | None = None, strict: bool = True) -> DataContract

Infer a contract from frame (alias for infer_from).

validate

validate(frame: pd.DataFrame) -> ValidationReport

Check frame against this contract and return a validation report.

check

check(frame: pd.DataFrame) -> DriftReport

Compare 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]) -> DataContract

Rebuild a contract from to_dict output.

to_json

to_json(**kwargs: object) -> str

Serialize the contract to JSON.

from_json

from_json(text: str) -> DataContract

Parse a contract from JSON.

to_yaml

to_yaml() -> str

Serialize to YAML (requires the optional pyyaml package).

from_yaml

from_yaml(text: str) -> DataContract

Parse 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:

NameTypeDescriptionDefault
findingspd.DataFramerequired
rowsint0

empty

empty() -> DriftReport

data_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:

NameTypeDescriptionDefault
findingspd.DataFramerequired
rowsint0
chunksint0

empty

empty() -> TransformReport

to_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]) -> TransformReport

Roll per-chunk DriftReport objects into one run-level report.

Parameters:

NameTypeDescriptionDefault
reportsIterable[DriftReport]

Reports from DataCleaner.transform_chunks or DataCleaner.transform_with_report, in chunk order. An empty iterable is allowed.

required

Returns:

TypeDescription
TransformReport

Findings concatenated in chunk order, with summed rows and the number of chunks. The aggregated report is the right object to log or persist for a whole batch job; individual chunk reports remain independent.

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:

NameTypeDescriptionDefault
sourcestrrequired
rowsintrequired
columnspd.DataFramerequired
findingspd.DataFramerequired
sheetstr | NoneNone

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() -> str

Return a short human-readable description of the findings.

to_markdown

to_markdown() -> str

Render 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') -> None

Raise 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:

NameTypeDescriptionDefault
sourcestr | os.PathLike[str] | IO[Any]

Path or file-like object accepted by pandas.read_csv.

required
contractDataContract | None

Optional DataContract. Declared columns use their role, dtype, and date format. Undeclared columns are inferred conservatively and reported as undeclared_column; the report lists their detected and output kinds.

None
on_errorIngestionPolicy

"warn" logs error findings and returns the frame (default), "raise" raises IngestionError when an error finding exists, and "ignore" suppresses logging while still returning the report.

'warn'
**read_csv_kwargsAny

Extra options passed to pandas.read_csv. Options that would bypass the string-first read (dtype, dtype_backend, na_filter, keep_default_na, na_values, parse_dates, converters, decimal, thousands, true_values, or false_values) are rejected.

required

Returns:

TypeDescription
tuple[pandas.DataFrame, IngestionReport]

The typed frame and an audit report. String columns are kept as object dtype for consistency across pandas 2.x and 3.x.

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:

NameTypeDescriptionDefault
sourcestr | os.PathLike[str] | IO[Any]

Path or file-like object accepted by pandas.read_csv.

required
contractDataContract | None

Optional DataContract. Passing a contract keeps typing consistent across chunks. Without one, the schema is inferred from the first chunk and reused for every later chunk, so a later value that does not fit the inferred type is reported instead of silently changing the column’s dtype.

None
chunksizeint

Number of rows per chunk. Must be a positive integer.

100000
on_errorIngestionPolicy

"warn" logs findings, "raise" raises IngestionError on the first failing chunk, and "ignore" suppresses logging.

'warn'
unique_trackingLiteral['memory', 'disk', 'auto']

Storage for the values already seen in unique=True columns. "memory" is fastest but grows with column cardinality. "disk" uses a temporary SQLite database and keeps peak memory flat. "auto" (default) starts in memory and migrates to disk once more than unique_tracking_limit values are tracked.

'auto'
unique_tracking_limitint

Number of tracked distinct values at which "auto" switches to disk.

1000000
unique_tracking_pathstr | 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_kwargsAny

Extra options passed to pandas.read_csv. The same reserved string-first options as read_csv_safe are rejected.

required

Yields:

TypeDescription
tuple[pandas.DataFrame, IngestionReport]

One typed frame and report per chunk. The report’s rows is the chunk size, not the file size.

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) -> IngestionReport

Roll per-chunk reports into one report for a whole file.

Parameters:

NameTypeDescriptionDefault
reportsIterable[IngestionReport]

Reports yielded by iter_csv_safe, in file order. An empty iterable is allowed and produces a report with zero rows.

required
sourcestr | None

Optional label for the combined report. Defaults to the source recorded on the first report.

None

Returns:

TypeDescription
IngestionReport

A report whose rows is the sum of the chunk sizes, whose findings concatenate every chunk’s findings in order, and whose columns table comes from the first chunk. sheet is taken from the first report.

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:

NameTypeDescriptionDefault
sourcestr | os.PathLike[str] | IO[Any]

Path or file-like object accepted by pandas.ExcelFile.

required
contractDataContract | None

Optional DataContract. Declared columns use their role, dtype, and date format. Undeclared columns are inferred conservatively and reported as undeclared_column; the report lists their detected and output kinds.

None
sheet_namestr | 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_errorIngestionPolicy

"warn" logs error findings and returns the frame (default), "raise" raises IngestionError when an error finding exists, and "ignore" suppresses logging while still returning the report.

'warn'
**read_excel_kwargsAny

Extra options passed to pandas.ExcelFile.parse. Options that would bypass the string-first read (dtype, dtype_backend, na_filter, keep_default_na, na_values, parse_dates, converters, decimal, thousands, true_values, or false_values) are rejected. engine, storage_options, and engine_kwargs are forwarded to pandas.ExcelFile so the matching pandas engine is used.

required

Returns:

TypeDescription
tuple[pandas.DataFrame, IngestionReport]

The typed frame and an audit report. String columns are kept as object dtype for consistency across pandas 2.x and 3.x.

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:

NameTypeDescriptionDefault
sourcestr | os.PathLike[str] | IO[Any]

Path or file-like object accepted by pandas.read_parquet.

required
contractDataContract | None

Optional DataContract. Declared columns use their role, dtype, and date format. Undeclared columns are inferred and reported as undeclared_column.

None
on_errorIngestionPolicy

"warn" logs error findings and returns the frame (default), "raise" raises IngestionError when an error finding exists, and "ignore" suppresses logging.

'warn'
**read_parquet_kwargsAny

Extra options passed to pandas.read_parquet. Options that would bypass the audit or the declared schema (columns, dtype, dtype_backend, engine, use_nullable_dtypes) are rejected.

required

Returns:

TypeDescription
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:

NameTypeDescriptionDefault
sourcestr | os.PathLike[str] | IO[Any]

Path or seekable file-like object accepted by pyarrow.parquet.ParquetFile.

required
contractDataContract | None

Optional DataContract. Without one, the schema is inferred from the first batch and reused for every later batch.

None
batch_sizeint

Rows per batch. Must be a positive integer.

100000
on_errorIngestionPolicy

"warn" logs findings, "raise" raises on the first failing batch, and "ignore" suppresses logging.

'warn'
unique_trackingLiteral['memory', 'disk', 'auto']

Same semantics as iter_csv_safe. Cross-batch uniqueness is checked for ColumnSpec(unique=True) columns.

'auto'
unique_tracking_limitint

Same semantics as iter_csv_safe. Cross-batch uniqueness is checked for ColumnSpec(unique=True) columns.

1000000
unique_tracking_pathstr | os.PathLike[str] | None

Same semantics as iter_csv_safe. Cross-batch uniqueness is checked for ColumnSpec(unique=True) columns.

None
**read_parquet_kwargsAny

Extra options accepted by pyarrow.parquet.ParquetFile.iter_batches, such as use_threads. Options that select or retype columns are rejected.

required

Yields:

TypeDescription
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:

NameTypeDescriptionDefault
sourcestr

Human-readable label for the batch, usually a file name.

required
overviewdict[str, object]

Dataset-level metrics from dataset_summary.

required
profilepd.DataFrame

Column-level profile from profile_dataframe.

required
driftDriftReport | None

Contract findings for the batch, when a contract is available.

None
validationValidationReport | None

Expectation results, when expectations are supplied.

None
ingestionIngestionReport | None

CSV or Excel ingestion findings, when the batch came from read_csv_safe or read_excel_safe.

None
decisionspd.DataFrame

The fitted cleaner’s decision log, when auditing with a cleaner.

<factory>
high_missing_thresholdfloat | None

Missing-percentage at which the profile emits a high_missing warning. Set to None to disable that warning.

50.0
library_versionstr

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) -> CleanerReport

Build a report for an in-memory DataFrame.

Parameters:

NameTypeDescriptionDefault
framepd.DataFrame

The batch to inspect. It is never modified.

required
sourcestr

Label recorded in the report.

'dataset'
namestr

Dataset name used in the column profile.

'dataset'
contractDataContract | None

Optional contract. When provided, its findings become the report’s contract section.

None
expectationsExpectation | Sequence[Expectation] | None

Optional expectation or sequence of expectations to evaluate.

None
ingestionIngestionReport | None

Optional ingestion report to attach, for example from read_csv_safe.

None
decisionspd.DataFrame | None

Optional decision log to attach, for example from a fitted cleaner.

None
include_profilebool

Compute the column-level profile. Disable it for very large batches when only findings are needed.

True
high_missing_thresholdfloat | None

Missing-percentage threshold for a high_missing warning.

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) -> CleanerReport

Read 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) -> CleanerReport

Read 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) -> CleanerReport

Audit 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() -> str

Return a short human-readable description of the report.

to_markdown

to_markdown() -> str

Render 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) -> str

Serialize the report to JSON.

raise_if_failed

raise_if_failed(message: str = 'Batch audit failed') -> None

Raise 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:

NameTypeDescriptionDefault
namestrrequired
columnstr | NoneNone
valuestuple[object, ...] | NoneNone
lowerfloat | NoneNone
upperfloat | NoneNone
inclusiveboolTrue
patternstr | NoneNone
dtypestr | NoneNone
min_rowsint | NoneNone
max_rowsint | NoneNone
severitySeverity'error'

check

check(frame: pd.DataFrame) -> ValidationResult

Evaluate this expectation against frame.

failing_mask

failing_mask(frame: pd.DataFrame) -> pd.Series | None

Return 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:

NameTypeDescriptionDefault
expectationstrrequired
columnstr | Nonerequired
successboolrequired
severitySeverityrequired
messagestrrequired
observedobjectNone

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:

NameTypeDescriptionDefault
resultspd.DataFramerequired
sourcestr'expectations'
sourcestuple[Validatable, ...]()

from_results

from_results(results: Sequence[ValidationResult], *, sources: tuple[Validatable, ...] = ()) -> ValidationReport

Build a report from individual results.

from_findings

from_findings(findings: pd.DataFrame) -> ValidationReport

Build 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() -> str

Return a short human-readable description of the failures.

to_markdown

to_markdown() -> str

Render the report as Markdown (falls back to plain text).

raise_if_failed

raise_if_failed(message: str = 'Validation failed') -> None

Raise 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) -> RowDiagnostics

Sample a bounded set of failing rows for this report.

Parameters:

NameTypeDescriptionDefault
framepd.DataFrame

The frame the report was produced from. It is never modified.

required
limitint

Maximum sampled rows per failing expectation or rule.

5
include_valuesbool

Include the failing value for rules that target a single column. Values are off by default because they may contain personal data.

False
include_indexbool

Include the frame index label for sampled rows. Labels are off by default when the index may contain identifiers; set this to False to return positions only.

True
max_value_lengthint

Truncate included values to this many characters.

32

Returns:

TypeDescription
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]) -> ValidationReport

Evaluate 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') -> Expectation

Expect column to contain no missing values.

data_cleaner.unique

unique(column: str, *, severity: Severity = 'error') -> Expectation

Expect non-null values in column to be unique.

data_cleaner.in_set

in_set(column: str, values: Sequence[object], *, severity: Severity = 'error') -> Expectation

Expect 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') -> Expectation

Expect numeric values in column to fall within the given bounds.

data_cleaner.matches_pattern

matches_pattern(column: str, pattern: str, *, severity: Severity = 'error') -> Expectation

Expect non-null string values in column to fully match pattern.

data_cleaner.has_dtype

has_dtype(column: str, dtype: str, *, severity: Severity = 'error') -> Expectation

Expect 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') -> Expectation

Expect 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.Series

Return a boolean mask aligned with frame.

known

known(frame: pd.DataFrame) -> pd.Series

Return 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() -> str

Return 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') -> PredicateRule

Turn this condition into a row-level rule.

data_cleaner.ColumnRef

A reference to a column inside a Condition.

eq

eq(other: object) -> Condition

Require equality with a value or another column.

ne

ne(other: object) -> Condition

Require inequality with a value or another column.

lt

lt(other: object) -> Condition

Require a value strictly less than other.

le

le(other: object) -> Condition

Require a value less than or equal to other.

gt

gt(other: object) -> Condition

Require a value strictly greater than other.

ge

ge(other: object) -> Condition

Require a value greater than or equal to other.

isin

isin(values: Sequence[object]) -> Condition

Require membership in values.

not_in

not_in(values: Sequence[object]) -> Condition

Require non-membership in values.

between

between(lower: object | None = None, upper: object | None = None, *, inclusive: bool = True) -> Condition

Require a value within the given bounds.

isna

isna() -> Condition

Require a missing value.

notna

notna() -> Condition

Require a present value.

matches

matches(pattern: str) -> Condition

Require a full-string regular-expression match.

data_cleaner.col

col(name: str) -> ColumnRef

Start a condition from a column reference.

data_cleaner.row_rule

row_rule(condition: Condition, *, name: str | None = None, severity: Severity = 'error') -> PredicateRule

Require 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:

NameTypeDescriptionDefault
conditionConditionrequired
namestrrequired
severitySeverity'error'
columnstr | NoneNone

value_column

The single column a failing value can be read from, if any.

check

check(frame: pd.DataFrame) -> ValidationResult

failing_mask

failing_mask(frame: pd.DataFrame) -> pd.Series | None

data_cleaner.conditional

conditional(condition: Condition, rule: Validatable, *, name: str | None = None, severity: Severity | None = None) -> ConditionalRule

Apply 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:

NameTypeDescriptionDefault
conditionConditionrequired
ruleValidatablerequired
namestrrequired
severitySeverity'error'
columnstr | NoneNone

value_column

The single column the inner rule reports a value for, if any.

check

check(frame: pd.DataFrame) -> ValidationResult

failing_mask

failing_mask(frame: pd.DataFrame) -> pd.Series | None

data_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) -> GroupedRule

Apply 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:

NameTypeDescriptionDefault
bytuple[str, ...]required
ruleValidatablerequired
namestrrequired
severitySeverity'error'
columnstr | NoneNone
max_groupsint10
include_groupsboolFalse

value_column

Grouped findings cannot be attributed to a single value.

check

check(frame: pd.DataFrame) -> ValidationResult

failing_mask

failing_mask(frame: pd.DataFrame) -> pd.Series | None

data_cleaner.unique_combination

unique_combination(columns: Sequence[str], *, name: str | None = None, severity: Severity = 'error') -> UniqueCombinationRule

Require 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:

NameTypeDescriptionDefault
columnstuple[str, ...]required
namestr'unique_combination'
severitySeverity'error'
columnstr | NoneNone

value_column

Only a single-column rule has a value to show.

check

check(frame: pd.DataFrame) -> ValidationResult

failing_mask

failing_mask(frame: pd.DataFrame) -> pd.Series | None

data_cleaner.sum_equals

sum_equals(columns: Sequence[str], target: str, *, tolerance: float = 1e-09, name: str | None = None, severity: Severity = 'error') -> SumEqualsRule

Require the numeric sum of columns to equal target per row.

data_cleaner.SumEqualsRuledataclass

Require the sum of columns to equal target within tolerance.

Parameters:

NameTypeDescriptionDefault
columnstuple[str, ...]required
targetstrrequired
tolerancefloatrequired
namestr'sum_equals'
severitySeverity'error'
columnstr | NoneNone

value_column

The target column is the value to show when a row fails.

check

check(frame: pd.DataFrame) -> ValidationResult

failing_mask

failing_mask(frame: pd.DataFrame) -> pd.Series | None

data_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:

NameTypeDescriptionDefault
rowspd.DataFramerequired
truncatedboolFalse
skippedtuple[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() -> str

Render 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:

NameTypeDescriptionDefault
psi_warningfloat | None0.1
psi_errorfloat | None0.25
wasserstein_warningfloat | NoneNone
wasserstein_errorfloat | NoneNone
missing_delta_warningfloat | None5.0
missing_delta_errorfloat | NoneNone
category_delta_warningfloat | None10.0
category_delta_errorfloat | NoneNone
min_sampleint20
binsint10
max_categoriesint20
max_columnsint200
wasserstein_pointsint512

to_dict

to_dict() -> dict[str, object]

Return a JSON-serializable representation of the policy.

from_dict

from_dict(data: dict[str, object]) -> DriftPolicy

Rebuild a policy from to_dict output.

to_json

to_json(**kwargs: object) -> str

Serialize the policy to JSON.

from_json

from_json(text: str) -> DriftPolicy

Parse 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:

NameTypeDescriptionDefault
columnsdict[str, _ColumnProfile]required
policyDriftPolicyrequired
rowsintrequired
skipped_columnstuple[str, ...]()

from_frame

from_frame(frame: pd.DataFrame, *, columns: list[str] | tuple[str, ...] | None = None, policy: DriftPolicy | None = None) -> DriftProfile

Profile a reference frame.

Parameters:

NameTypeDescriptionDefault
framepd.DataFrame

Reference data. It is never modified.

required
columnslist[str] | tuple[str, ...] | None

Columns to profile. When omitted, every numeric, categorical, boolean, and datetime column is profiled, up to policy.max_columns in frame order. An explicit list is never truncated.

None
policyDriftPolicy | None

Thresholds and sampling controls stored with the profile.

None

Raises:

TypeDescription
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) -> DistributionDriftReport

Compare 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]) -> DriftProfile

Rebuild a profile from to_dict output.

to_json

to_json(**kwargs: object) -> str

Serialize the profile to JSON.

from_json

from_json(text: str) -> DriftProfile

Parse 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:

NameTypeDescriptionDefault
columnspd.DataFramerequired
categoriespd.DataFramerequired
reference_rowsintrequired
current_rowsintrequired
policyDriftPolicyrequired
referenceDriftProfile | NoneNone

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() -> str

Return a short human-readable description of the drift.

to_markdown

to_markdown() -> str

Render 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) -> str

Serialize the report to JSON.

raise_if_drift

raise_if_drift(message: str = 'Statistical drift detected') -> None

Raise 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) -> DistributionDriftReport

Compare 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:

NameTypeDescriptionDefault
pathstr | os.PathLike[str]

Destination file. It is created on first write.

required
create_parentsbool

Create missing parent directories when the sink is constructed.

True
fsyncbool

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.DataFrame

Return a one-row-per-batch summary of the stored records.

latest

latest(*, kind: str | None = None, source: str | None = None) -> dict[str, object] | None

Return 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) -> DistributionDriftReport

Compare 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:

NameTypeDescriptionDefault
howstrrequired
ontuple[str, ...]required
validatestr | Nonerequired
left_rowsintrequired
right_rowsintrequired
output_rowsintrequired
row_multiplierfloatrequired
left_cardinalitystrrequired
right_cardinalitystrrequired
cardinalitystrrequired
cardinality_matchesboolrequired
left_duplicate_keysintrequired
right_duplicate_keysintrequired
left_duplicate_rowsintrequired
right_duplicate_rowsintrequired
left_null_keysintrequired
right_null_keysintrequired
unmatched_leftintrequired
unmatched_rightintrequired
safeboolrequired
warningstuple[str, ...]required

to_dict

to_dict() -> dict[str, object]

Return a JSON-friendly representation of the diagnosis.

to_markdown

to_markdown() -> str

Render the diagnosis as a Markdown table.

raise_if_unsafe

raise_if_unsafe(message: str = 'Join is not safe') -> None

Raise 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') -> JoinDiagnosis

Diagnose key duplication, cardinality, and row preservation for a join.

Parameters:

NameTypeDescriptionDefault
leftpd.DataFrame

Frames to join. Only key columns are inspected.

required
rightpd.DataFrame

Frames to join. Only key columns are inspected.

required
onstr | Sequence[str]

Key column name or names. Both frames must contain every key.

required
howJoinHow

One of "left", "right", "inner", or "outer".

'left'
validateJoinCardinality | None

Expected maximum cardinality: "1:1", "1:m", "m:1", "m:m", or None to skip the cardinality check.

'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:

NameTypeDescriptionDefault
child_keytuple[str, ...]required
parent_keytuple[str, ...]required
child_rowsintrequired
parent_rowsintrequired
matched_rowsintrequired
orphan_rowsintrequired
orphan_key_countintrequired
orphan_keystuple[tuple[object, ...], ...]required
null_child_keysintrequired
null_parent_keysintrequired
parent_duplicate_keysintrequired
validboolrequired
warningstuple[str, ...]required

to_dict

to_dict() -> dict[str, object]

Return a JSON-friendly representation of the report.

to_markdown

to_markdown() -> str

Render the report as a Markdown table.

raise_if_invalid

raise_if_invalid(message: str = 'Referential integrity check failed') -> None

Raise 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) -> ReferentialIntegrityReport

Check 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:

NameTypeDescriptionDefault
keytuple[str, ...]required
keepstrrequired
tie_breakertuple[str, ...] | Nonerequired
input_rowsintrequired
output_rowsintrequired
removed_rowsintrequired
duplicate_keysintrequired
null_key_rowsintrequired
removedpd.DataFramerequired
warningstuple[str, ...]required

to_dict

to_dict() -> dict[str, object]

Return a JSON-friendly summary (without the removed rows).

to_markdown

to_markdown() -> str

Render 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:

NameTypeDescriptionDefault
findingspd.DataFramerequired
train_rowsintrequired
test_rowsintrequired
taskResolvedTask | Nonerequired
duplicate_overlap_rowsint0
near_duplicate_overlap_rowsint0
group_overlapint0
time_overlap_rowsint0

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() -> str

Return a short human-readable description of the findings.

to_markdown

to_markdown() -> str

Render 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') -> None

Raise 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) -> SplitAudit

Audit a train/test split for leakage and distribution problems.

Parameters:

NameTypeDescriptionDefault
X_trainpd.DataFrame

Feature frames. They are never modified.

required
X_testpd.DataFrame

Feature frames. They are never modified.

required
y_trainSequence[object] | pd.Series | np.ndarray | None

Optional targets, aligned by position. Both must be supplied together.

None
y_testSequence[object] | pd.Series | np.ndarray | None

Optional targets, aligned by position. Both must be supplied together.

None
groupsSequence[object] | pd.Series | np.ndarray | None

Group labels for the training rows. If groups_test is omitted, groups may contain len(X_train) + len(X_test) labels; the trailing labels are used for the test rows.

None
groups_testSequence[object] | pd.Series | np.ndarray | None

Group labels for the test rows when groups only covers train.

None
time_colstr | 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_colsstr | Sequence[str] | None

Optional identifier columns. They are excluded from duplicate, constant, distribution, and target-leakage checks. Declared identifiers are still reported under high_cardinality_identifier when their cardinality is high.

None
taskTaskType

"auto", "classification", or "regression". "auto" infers classification from a boolean, categorical, string, or low-cardinality integer target. It is ignored when targets are omitted or the training target is entirely null.

'auto'
near_duplicate_decimalsint | None

Decimal places used to round numeric features before near-duplicate detection. None disables near-duplicate checks.

3
constant_thresholdfloat

Share of the most frequent value at or above which a column is near-constant.

0.99
high_cardinality_thresholdfloat

Unique-value share at or above which a column is high-cardinality.

0.9
high_cardinality_min_uniqueint

Minimum number of unique values before a column is called high-cardinality.

20
missingness_shift_thresholdfloat

Absolute missing-rate change at or above which a finding is emitted.

0.1
distribution_shift_thresholdfloat

Standardized mean difference at or above which a numeric feature is reported as shifted.

0.5
categorical_shift_thresholdfloat

Total variation distance at or above which a categorical feature is reported as shifted.

0.2
target_correlation_thresholdfloat

Absolute correlation at or above which a numeric feature is suspected of target leakage.

0.95
target_nmi_thresholdfloat

Normalized mutual information at or above which a categorical feature is suspected of target leakage.

0.9
target_shift_thresholdfloat

Target-distribution shift threshold. Used as total variation distance for classification and standardized mean difference for regression.

0.5
classification_max_classesint

Maximum unique integer target values inferred as classification when task="auto".

20
max_target_leak_categoriesint

Maximum feature cardinality considered for the categorical target-leakage heuristic.

50

Returns:

TypeDescription
SplitAudit

A severity-tagged findings table plus convenience properties and raise_if_invalid().

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) -> str

Return 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:

NameTypeDescriptionDefault
framepd.DataFrame

DataFrame to fingerprint.

required
columnsSequence[str] | None

Optional subset/order of columns. Defaults to all columns in frame order.

None

Raises:

TypeDescription
TypeError

If frame is not a pandas DataFrame.

ValueError

If frame has duplicate column names.

KeyError

If a requested column is missing from frame.

data_cleaner.compare_fingerprints

compare_fingerprints(left: str, right: str) -> bool

Return True when two fingerprints are identical.

data_cleaner.assert_schema_stable

assert_schema_stable(frame: pd.DataFrame, expected: str, *, name: str = 'frame') -> None

Raise 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.DataFrame

Create 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) -> None

Assert that a cleaned frame has no missing/infinite values.

The package follows semantic versioning for its public API.

TierWhat it coversGuarantee
StableEvery name in data_cleaner.__all__No breaking change in the 2.x line
ExperimentalNames documented as experimentalMay change in a minor release; keep usage isolated
InternalModules 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 DeprecationWarning and 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.