universal-data-cleaner 2.7.0__tar.gz → 2.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/PKG-INFO +16 -4
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/README.md +13 -3
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/pyproject.toml +5 -1
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/__init__.py +11 -2
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/__main__.py +52 -12
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/_version.py +1 -1
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/cleaner.py +102 -18
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/config.py +12 -1
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/contract.py +6 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/ingestion.py +503 -85
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/integration.py +48 -10
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/reporting.py +49 -3
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/universal_data_cleaner.egg-info/PKG-INFO +16 -4
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/universal_data_cleaner.egg-info/SOURCES.txt +1 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/universal_data_cleaner.egg-info/requires.txt +3 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/tests/test_data_cleaner.py +123 -2
- universal_data_cleaner-2.9.0/tests/test_excel_ingestion.py +443 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/tests/test_ingestion.py +37 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/tests/test_validation.py +19 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/LICENSE +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/setup.cfg +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/_roles.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/artifacts.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/decisions.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/ml_audit.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/profiling.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/py.typed +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/data_cleaner/validation.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/universal_data_cleaner.egg-info/dependency_links.txt +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/universal_data_cleaner.egg-info/entry_points.txt +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/src/universal_data_cleaner.egg-info/top_level.txt +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/tests/test_ml_audit.py +0 -0
- {universal_data_cleaner-2.7.0 → universal_data_cleaner-2.9.0}/tests/test_reporting.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: universal-data-cleaner
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.9.0
|
|
4
4
|
Summary: Production-ready, scikit-learn-compatible data cleaning transformer for pandas.
|
|
5
5
|
Author: Haseeb Khan
|
|
6
6
|
License-Expression: MIT
|
|
@@ -30,6 +30,8 @@ Requires-Dist: pandas>=2.2
|
|
|
30
30
|
Requires-Dist: numpy>=1.26
|
|
31
31
|
Requires-Dist: scikit-learn>=1.4
|
|
32
32
|
Requires-Dist: joblib>=1.3
|
|
33
|
+
Provides-Extra: excel
|
|
34
|
+
Requires-Dist: openpyxl>=3.1; extra == "excel"
|
|
33
35
|
Dynamic: license-file
|
|
34
36
|
|
|
35
37
|
# Universal Data Cleaner
|
|
@@ -58,7 +60,7 @@ The docs site is the central reference. This README is the short entry point.
|
|
|
58
60
|
| [Leak-safe workflow](https://devlprkhan.github.io/universal-data-cleaner/leak-safe-workflow/) | The fit/transform contract and common mistakes |
|
|
59
61
|
| [Cleaning data](https://devlprkhan.github.io/universal-data-cleaner/cleaning/) | Config, roles, imputation, outliers, datetimes |
|
|
60
62
|
| [Contracts & drift](https://devlprkhan.github.io/universal-data-cleaner/contracts/) | `ColumnSpec`, `DataContract`, drift checks |
|
|
61
|
-
| [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads
|
|
63
|
+
| [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV and Excel reads with ingestion reports |
|
|
62
64
|
| [Batch reporting](https://devlprkhan.github.io/universal-data-cleaner/reporting/) | `CleanerReport` and the `data-cleaner audit` CLI |
|
|
63
65
|
| [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
|
|
64
66
|
| [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
|
|
@@ -81,6 +83,16 @@ uv add universal-data-cleaner
|
|
|
81
83
|
The distribution name is `universal-data-cleaner`; the import name is
|
|
82
84
|
`data_cleaner`.
|
|
83
85
|
|
|
86
|
+
For Excel input, install the optional extra:
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
pip install "universal-data-cleaner[excel]"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
uv add "universal-data-cleaner[excel]"
|
|
94
|
+
```
|
|
95
|
+
|
|
84
96
|
```python
|
|
85
97
|
from data_cleaner import CleanerConfig, DataCleaner
|
|
86
98
|
```
|
|
@@ -134,8 +146,8 @@ for the full explanation.
|
|
|
134
146
|
- boolean coercion and imputation
|
|
135
147
|
- datetime parsing plus calendar feature extraction
|
|
136
148
|
- optional missing-value indicators and constant-column dropping
|
|
137
|
-
- safe CSV ingestion with contract-driven coercion, identifier
|
|
138
|
-
and boolean guards, and an audit report
|
|
149
|
+
- safe CSV and Excel ingestion with contract-driven coercion, identifier
|
|
150
|
+
protection, date and boolean guards, and an audit report
|
|
139
151
|
- `CleanerReport` combining profile, contract drift, validation, ingestion, and
|
|
140
152
|
cleaner decisions, plus a `data-cleaner audit` CLI
|
|
141
153
|
- declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
|
|
@@ -24,7 +24,7 @@ The docs site is the central reference. This README is the short entry point.
|
|
|
24
24
|
| [Leak-safe workflow](https://devlprkhan.github.io/universal-data-cleaner/leak-safe-workflow/) | The fit/transform contract and common mistakes |
|
|
25
25
|
| [Cleaning data](https://devlprkhan.github.io/universal-data-cleaner/cleaning/) | Config, roles, imputation, outliers, datetimes |
|
|
26
26
|
| [Contracts & drift](https://devlprkhan.github.io/universal-data-cleaner/contracts/) | `ColumnSpec`, `DataContract`, drift checks |
|
|
27
|
-
| [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads
|
|
27
|
+
| [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV and Excel reads with ingestion reports |
|
|
28
28
|
| [Batch reporting](https://devlprkhan.github.io/universal-data-cleaner/reporting/) | `CleanerReport` and the `data-cleaner audit` CLI |
|
|
29
29
|
| [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
|
|
30
30
|
| [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
|
|
@@ -47,6 +47,16 @@ uv add universal-data-cleaner
|
|
|
47
47
|
The distribution name is `universal-data-cleaner`; the import name is
|
|
48
48
|
`data_cleaner`.
|
|
49
49
|
|
|
50
|
+
For Excel input, install the optional extra:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install "universal-data-cleaner[excel]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
uv add "universal-data-cleaner[excel]"
|
|
58
|
+
```
|
|
59
|
+
|
|
50
60
|
```python
|
|
51
61
|
from data_cleaner import CleanerConfig, DataCleaner
|
|
52
62
|
```
|
|
@@ -100,8 +110,8 @@ for the full explanation.
|
|
|
100
110
|
- boolean coercion and imputation
|
|
101
111
|
- datetime parsing plus calendar feature extraction
|
|
102
112
|
- optional missing-value indicators and constant-column dropping
|
|
103
|
-
- safe CSV ingestion with contract-driven coercion, identifier
|
|
104
|
-
and boolean guards, and an audit report
|
|
113
|
+
- safe CSV and Excel ingestion with contract-driven coercion, identifier
|
|
114
|
+
protection, date and boolean guards, and an audit report
|
|
105
115
|
- `CleanerReport` combining profile, contract drift, validation, ingestion, and
|
|
106
116
|
cleaner decisions, plus a `data-cleaner audit` CLI
|
|
107
117
|
- declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "universal-data-cleaner"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.9.0"
|
|
8
8
|
description = "Production-ready, scikit-learn-compatible data cleaning transformer for pandas."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -43,6 +43,9 @@ dependencies = [
|
|
|
43
43
|
"joblib>=1.3",
|
|
44
44
|
]
|
|
45
45
|
|
|
46
|
+
[project.optional-dependencies]
|
|
47
|
+
excel = ["openpyxl>=3.1"]
|
|
48
|
+
|
|
46
49
|
[project.urls]
|
|
47
50
|
Homepage = "https://github.com/devlprkhan/universal-data-cleaner"
|
|
48
51
|
Documentation = "https://devlprkhan.github.io/universal-data-cleaner/"
|
|
@@ -64,6 +67,7 @@ dev = [
|
|
|
64
67
|
"mypy>=2.4.0",
|
|
65
68
|
"nbclient>=0.11.0",
|
|
66
69
|
"nbformat>=5.11.1",
|
|
70
|
+
"openpyxl>=3.1",
|
|
67
71
|
"pandas-stubs>=2.3.3.260113",
|
|
68
72
|
"pre-commit>=4.6.2",
|
|
69
73
|
"pytest>=9.1.1",
|
|
@@ -18,11 +18,17 @@ from .artifacts import (
|
|
|
18
18
|
compare_fingerprints,
|
|
19
19
|
fingerprint_dataframe,
|
|
20
20
|
)
|
|
21
|
-
from .cleaner import DataCleaner
|
|
21
|
+
from .cleaner import ArtifactCompatibilityError, DataCleaner
|
|
22
22
|
from .config import CleanerConfig
|
|
23
23
|
from .contract import ColumnSpec, Contract, DataContract, DriftReport
|
|
24
24
|
from .decisions import CleaningDecision
|
|
25
|
-
from .ingestion import
|
|
25
|
+
from .ingestion import (
|
|
26
|
+
IngestionError,
|
|
27
|
+
IngestionReport,
|
|
28
|
+
iter_csv_safe,
|
|
29
|
+
read_csv_safe,
|
|
30
|
+
read_excel_safe,
|
|
31
|
+
)
|
|
26
32
|
from .integration import (
|
|
27
33
|
DeduplicationReport,
|
|
28
34
|
JoinDiagnosis,
|
|
@@ -54,6 +60,7 @@ from .validation import (
|
|
|
54
60
|
)
|
|
55
61
|
|
|
56
62
|
__all__ = [
|
|
63
|
+
"ArtifactCompatibilityError",
|
|
57
64
|
"CleanerConfig",
|
|
58
65
|
"CleanerReport",
|
|
59
66
|
"CleaningDecision",
|
|
@@ -85,10 +92,12 @@ __all__ = [
|
|
|
85
92
|
"fingerprint_dataframe",
|
|
86
93
|
"has_dtype",
|
|
87
94
|
"in_set",
|
|
95
|
+
"iter_csv_safe",
|
|
88
96
|
"matches_pattern",
|
|
89
97
|
"not_null",
|
|
90
98
|
"profile_dataframe",
|
|
91
99
|
"read_csv_safe",
|
|
100
|
+
"read_excel_safe",
|
|
92
101
|
"row_count_between",
|
|
93
102
|
"unique",
|
|
94
103
|
"validate",
|
|
@@ -4,14 +4,19 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import argparse
|
|
6
6
|
import sys
|
|
7
|
+
import zipfile
|
|
7
8
|
from pathlib import Path
|
|
8
9
|
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
9
12
|
from ._version import __version__
|
|
10
13
|
from .cleaner import DataCleaner
|
|
11
14
|
from .contract import DataContract
|
|
12
|
-
from .ingestion import read_csv_safe
|
|
15
|
+
from .ingestion import IngestionReport, read_csv_safe, read_excel_safe
|
|
13
16
|
from .reporting import CleanerReport
|
|
14
17
|
|
|
18
|
+
_EXCEL_SUFFIXES = {".xls", ".xlsb", ".xlsm", ".xlsx", ".ods"}
|
|
19
|
+
|
|
15
20
|
|
|
16
21
|
def build_parser() -> argparse.ArgumentParser:
|
|
17
22
|
"""Build the ``python -m data_cleaner`` argument parser."""
|
|
@@ -28,13 +33,33 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
28
33
|
|
|
29
34
|
audit = subparsers.add_parser(
|
|
30
35
|
"audit",
|
|
31
|
-
help="Audit a CSV batch and print a report.",
|
|
36
|
+
help="Audit a CSV or Excel batch and print a report.",
|
|
32
37
|
description=(
|
|
33
|
-
"Read a CSV safely, then report its profile, contract
|
|
34
|
-
"and cleaner decisions."
|
|
38
|
+
"Read a CSV or Excel file safely, then report its profile, contract "
|
|
39
|
+
"findings, and cleaner decisions."
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
audit.add_argument("path", type=Path, help="CSV or Excel file to audit.")
|
|
43
|
+
sheet = audit.add_mutually_exclusive_group()
|
|
44
|
+
sheet.add_argument(
|
|
45
|
+
"--sheet",
|
|
46
|
+
default=None,
|
|
47
|
+
metavar="NAME",
|
|
48
|
+
help=(
|
|
49
|
+
"Excel worksheet name (defaults to the first sheet); only valid for "
|
|
50
|
+
"Excel input."
|
|
51
|
+
),
|
|
52
|
+
)
|
|
53
|
+
sheet.add_argument(
|
|
54
|
+
"--sheet-index",
|
|
55
|
+
type=int,
|
|
56
|
+
default=None,
|
|
57
|
+
metavar="N",
|
|
58
|
+
help=(
|
|
59
|
+
"Zero-based Excel worksheet index; only valid for Excel input and "
|
|
60
|
+
"mutually exclusive with --sheet."
|
|
35
61
|
),
|
|
36
62
|
)
|
|
37
|
-
audit.add_argument("csv", type=Path, help="CSV file to audit.")
|
|
38
63
|
source = audit.add_mutually_exclusive_group()
|
|
39
64
|
source.add_argument(
|
|
40
65
|
"--contract",
|
|
@@ -80,6 +105,24 @@ def _load_contract(path: Path) -> DataContract:
|
|
|
80
105
|
return DataContract.from_json(path.read_text(encoding="utf-8"))
|
|
81
106
|
|
|
82
107
|
|
|
108
|
+
def _read_input(
|
|
109
|
+
path: Path, contract: DataContract | None, sheet: str | int | None
|
|
110
|
+
) -> tuple[pd.DataFrame, IngestionReport]:
|
|
111
|
+
"""Read a CSV or Excel input and return its ingestion report."""
|
|
112
|
+
if path.suffix.lower() in _EXCEL_SUFFIXES:
|
|
113
|
+
frame, ingestion = read_excel_safe(
|
|
114
|
+
path,
|
|
115
|
+
contract=contract,
|
|
116
|
+
sheet_name=0 if sheet is None else sheet,
|
|
117
|
+
on_error="ignore",
|
|
118
|
+
)
|
|
119
|
+
return frame, ingestion
|
|
120
|
+
if sheet is not None:
|
|
121
|
+
raise ValueError("--sheet is only valid for Excel input")
|
|
122
|
+
frame, ingestion = read_csv_safe(path, contract=contract, on_error="ignore")
|
|
123
|
+
return frame, ingestion
|
|
124
|
+
|
|
125
|
+
|
|
83
126
|
def _run_audit(args: argparse.Namespace) -> int:
|
|
84
127
|
contract: DataContract | None = None
|
|
85
128
|
cleaner: DataCleaner | None = None
|
|
@@ -89,12 +132,9 @@ def _run_audit(args: argparse.Namespace) -> int:
|
|
|
89
132
|
cleaner = DataCleaner.load(args.cleaner)
|
|
90
133
|
contract = cleaner.fitted_contract()
|
|
91
134
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
on_error="ignore",
|
|
96
|
-
)
|
|
97
|
-
dataset_name = args.name or args.csv.stem
|
|
135
|
+
sheet = args.sheet if args.sheet is not None else args.sheet_index
|
|
136
|
+
frame, ingestion = _read_input(args.path, contract, sheet)
|
|
137
|
+
dataset_name = args.name or args.path.stem
|
|
98
138
|
if cleaner is not None:
|
|
99
139
|
report = CleanerReport.from_cleaner(
|
|
100
140
|
cleaner,
|
|
@@ -137,7 +177,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
137
177
|
if args.command == "audit":
|
|
138
178
|
try:
|
|
139
179
|
return _run_audit(args)
|
|
140
|
-
except (OSError, ValueError,
|
|
180
|
+
except (ImportError, OSError, TypeError, ValueError, zipfile.BadZipFile) as exc:
|
|
141
181
|
print(f"error: {exc}", file=sys.stderr)
|
|
142
182
|
return 2
|
|
143
183
|
parser.print_help()
|
|
@@ -26,6 +26,18 @@ from .decisions import DECISION_COLUMNS, CleaningDecision
|
|
|
26
26
|
LOGGER = logging.getLogger(__name__)
|
|
27
27
|
|
|
28
28
|
|
|
29
|
+
class ArtifactCompatibilityError(RuntimeError):
|
|
30
|
+
"""Raised when a saved artifact cannot be loaded by this library version."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _major_version(version: object) -> int | None:
|
|
34
|
+
"""Return the major component of a version string, or ``None``."""
|
|
35
|
+
try:
|
|
36
|
+
return int(str(version).split(".", 1)[0])
|
|
37
|
+
except (TypeError, ValueError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
29
41
|
class DataCleaner(TransformerMixin, BaseEstimator):
|
|
30
42
|
"""Fit/transform data cleaner that prevents train/test leakage.
|
|
31
43
|
|
|
@@ -40,11 +52,13 @@ class DataCleaner(TransformerMixin, BaseEstimator):
|
|
|
40
52
|
def fit(self, X: pd.DataFrame, y: object | None = None) -> DataCleaner:
|
|
41
53
|
"""Learn cleaning rules from training data."""
|
|
42
54
|
frame = self._validate_frame(X, required=None, allow_empty=False)
|
|
55
|
+
self._validate_training_contract(frame)
|
|
43
56
|
self.decisions_: list[CleaningDecision] = []
|
|
44
57
|
self.contract_ = self._resolve_contract(frame)
|
|
45
58
|
self._record_contract_decision()
|
|
46
59
|
frame = self._drop_ignored_columns(frame)
|
|
47
60
|
roles = self._infer_roles(frame)
|
|
61
|
+
self._validate_outlier_columns(roles)
|
|
48
62
|
self.id_columns_ = [
|
|
49
63
|
column for column in frame.columns if self._role_for(column) == "id"
|
|
50
64
|
]
|
|
@@ -410,6 +424,34 @@ class DataCleaner(TransformerMixin, BaseEstimator):
|
|
|
410
424
|
return deepcopy(stored)
|
|
411
425
|
return self.to_manifest(X, include_fingerprint=include_fingerprint)
|
|
412
426
|
|
|
427
|
+
def _validate_training_contract(self, frame: pd.DataFrame) -> None:
|
|
428
|
+
"""Fail fast when a required explicit-contract column is absent."""
|
|
429
|
+
contract = self.config.contract
|
|
430
|
+
if contract is None:
|
|
431
|
+
return
|
|
432
|
+
missing = [
|
|
433
|
+
spec.name
|
|
434
|
+
for spec in contract.columns
|
|
435
|
+
if spec.required
|
|
436
|
+
and spec.role != "ignore"
|
|
437
|
+
and spec.name not in frame.columns
|
|
438
|
+
]
|
|
439
|
+
if missing:
|
|
440
|
+
raise ValueError(
|
|
441
|
+
"Training data is missing required contract columns: "
|
|
442
|
+
f"{missing}. Add them to the training frame or set "
|
|
443
|
+
"required=False on the column spec."
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
def _validate_outlier_columns(self, roles: dict[str, str]) -> None:
|
|
447
|
+
"""Ensure explicit outlier columns resolve to numeric columns."""
|
|
448
|
+
configured = self.config.outlier_columns
|
|
449
|
+
if not configured:
|
|
450
|
+
return
|
|
451
|
+
invalid = [column for column in configured if roles.get(column) != "numeric"]
|
|
452
|
+
if invalid:
|
|
453
|
+
raise ValueError(f"outlier_columns must name numeric columns: {invalid}")
|
|
454
|
+
|
|
413
455
|
def _resolve_contract(self, frame: pd.DataFrame) -> DataContract | None:
|
|
414
456
|
if self.config.contract is not None:
|
|
415
457
|
return self.config.contract
|
|
@@ -479,8 +521,21 @@ class DataCleaner(TransformerMixin, BaseEstimator):
|
|
|
479
521
|
return target
|
|
480
522
|
|
|
481
523
|
@classmethod
|
|
482
|
-
def load(
|
|
483
|
-
|
|
524
|
+
def load(
|
|
525
|
+
cls,
|
|
526
|
+
path: str | Path,
|
|
527
|
+
verify_version: bool = True,
|
|
528
|
+
*,
|
|
529
|
+
allow_incompatible: bool = False,
|
|
530
|
+
) -> DataCleaner:
|
|
531
|
+
"""Load a saved cleaner artifact and restore its manifest.
|
|
532
|
+
|
|
533
|
+
Artifacts written by a different artifact format version or a different
|
|
534
|
+
library major version are refused by default. Pass
|
|
535
|
+
``allow_incompatible=True`` to load them with a warning, or
|
|
536
|
+
``verify_version=False`` to skip the compatibility check entirely.
|
|
537
|
+
``joblib.load`` uses pickle, so only load artifacts you trust.
|
|
538
|
+
"""
|
|
484
539
|
payload = joblib.load(Path(path))
|
|
485
540
|
if not isinstance(payload, dict) or "cleaner" not in payload:
|
|
486
541
|
raise ValueError("File is not a valid DataCleaner artifact")
|
|
@@ -488,6 +543,48 @@ class DataCleaner(TransformerMixin, BaseEstimator):
|
|
|
488
543
|
if not isinstance(cleaner, cls):
|
|
489
544
|
raise TypeError("Artifact does not contain a DataCleaner")
|
|
490
545
|
|
|
546
|
+
artifact_version = payload.get("artifact_version")
|
|
547
|
+
library_version = payload.get("library_version")
|
|
548
|
+
|
|
549
|
+
incompatible: list[str] = []
|
|
550
|
+
if artifact_version is None:
|
|
551
|
+
incompatible.append("Artifact format version is missing")
|
|
552
|
+
elif artifact_version != _ARTIFACT_VERSION:
|
|
553
|
+
incompatible.append(
|
|
554
|
+
f"Artifact version {artifact_version} is not the current "
|
|
555
|
+
f"version {_ARTIFACT_VERSION}"
|
|
556
|
+
)
|
|
557
|
+
if library_version is None:
|
|
558
|
+
incompatible.append("Artifact library version is missing")
|
|
559
|
+
elif _major_version(library_version) != _major_version(__version__):
|
|
560
|
+
incompatible.append(
|
|
561
|
+
f"Artifact was created with library {library_version}; the "
|
|
562
|
+
f"current version is {__version__}"
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
if verify_version and incompatible:
|
|
566
|
+
reason = "; ".join(incompatible)
|
|
567
|
+
if not allow_incompatible:
|
|
568
|
+
raise ArtifactCompatibilityError(
|
|
569
|
+
f"Cannot load incompatible artifact: {reason}. Retrain and "
|
|
570
|
+
"save with the current version, or pass "
|
|
571
|
+
"allow_incompatible=True only if you accept the risk."
|
|
572
|
+
)
|
|
573
|
+
LOGGER.warning(
|
|
574
|
+
"Loading incompatible artifact because allow_incompatible=True: %s",
|
|
575
|
+
reason,
|
|
576
|
+
)
|
|
577
|
+
elif (
|
|
578
|
+
verify_version
|
|
579
|
+
and library_version is not None
|
|
580
|
+
and library_version != __version__
|
|
581
|
+
):
|
|
582
|
+
LOGGER.warning(
|
|
583
|
+
"Artifact was created with library version %s, current version is %s",
|
|
584
|
+
library_version,
|
|
585
|
+
__version__,
|
|
586
|
+
)
|
|
587
|
+
|
|
491
588
|
manifest = payload.get("manifest")
|
|
492
589
|
if not isinstance(manifest, dict):
|
|
493
590
|
LOGGER.warning(
|
|
@@ -505,21 +602,6 @@ class DataCleaner(TransformerMixin, BaseEstimator):
|
|
|
505
602
|
)
|
|
506
603
|
if not hasattr(cleaner, "training_fingerprint_"):
|
|
507
604
|
cleaner.training_fingerprint_ = payload.get("fingerprint")
|
|
508
|
-
|
|
509
|
-
artifact_version = payload.get("artifact_version")
|
|
510
|
-
library_version = payload.get("library_version")
|
|
511
|
-
if verify_version and library_version != __version__:
|
|
512
|
-
LOGGER.warning(
|
|
513
|
-
"Artifact was created with library version %s, current version is %s",
|
|
514
|
-
library_version,
|
|
515
|
-
__version__,
|
|
516
|
-
)
|
|
517
|
-
if artifact_version != _ARTIFACT_VERSION:
|
|
518
|
-
LOGGER.warning(
|
|
519
|
-
"Artifact version %s is not the current version %s",
|
|
520
|
-
artifact_version,
|
|
521
|
-
_ARTIFACT_VERSION,
|
|
522
|
-
)
|
|
523
605
|
return cleaner
|
|
524
606
|
|
|
525
607
|
def _ensure_fitted(self) -> None:
|
|
@@ -818,8 +900,10 @@ class DataCleaner(TransformerMixin, BaseEstimator):
|
|
|
818
900
|
q1 = q3 = np.nan
|
|
819
901
|
outliers = 0
|
|
820
902
|
iqr = 0.0
|
|
903
|
+
selected = cfg.outlier_columns
|
|
904
|
+
cap_enabled = column in selected if selected else cfg.cap_outliers
|
|
821
905
|
should_cap = (
|
|
822
|
-
|
|
906
|
+
cap_enabled and roles.get(column) == "numeric" and not valid.empty
|
|
823
907
|
)
|
|
824
908
|
if should_cap:
|
|
825
909
|
q1 = float(valid.quantile(0.25))
|
|
@@ -17,8 +17,9 @@ class CleanerConfig:
|
|
|
17
17
|
categorical_imputation: Literal["mode", "constant"] = "mode"
|
|
18
18
|
numeric_fill_value: float = 0.0
|
|
19
19
|
categorical_fill_value: str = "Unknown"
|
|
20
|
-
cap_outliers: bool =
|
|
20
|
+
cap_outliers: bool = False
|
|
21
21
|
outlier_multiplier: float = 1.5
|
|
22
|
+
outlier_columns: tuple[str, ...] = ()
|
|
22
23
|
add_missing_indicators: bool = False
|
|
23
24
|
drop_constant_columns: bool = True
|
|
24
25
|
numeric_columns: tuple[str, ...] = ()
|
|
@@ -44,6 +45,7 @@ class CleanerConfig:
|
|
|
44
45
|
"categorical_columns",
|
|
45
46
|
"datetime_columns",
|
|
46
47
|
"datetime_features",
|
|
48
|
+
"outlier_columns",
|
|
47
49
|
):
|
|
48
50
|
object.__setattr__(self, name, tuple(getattr(self, name)))
|
|
49
51
|
|
|
@@ -82,3 +84,12 @@ class CleanerConfig:
|
|
|
82
84
|
raise ValueError(
|
|
83
85
|
f"{left_name} and {right_name} overlap: {sorted(left & right)}"
|
|
84
86
|
)
|
|
87
|
+
|
|
88
|
+
non_numeric_outliers = set(self.outlier_columns) & (
|
|
89
|
+
set(self.categorical_columns) | set(self.datetime_columns)
|
|
90
|
+
)
|
|
91
|
+
if non_numeric_outliers:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"outlier_columns must name numeric columns: "
|
|
94
|
+
f"{sorted(non_numeric_outliers)}"
|
|
95
|
+
)
|
|
@@ -29,6 +29,8 @@ class ColumnSpec:
|
|
|
29
29
|
``role`` tells the cleaner how the column should be treated
|
|
30
30
|
(``numeric``, ``category``, ``boolean``, ``datetime``, ``id``, ``text``,
|
|
31
31
|
``ignore``). The remaining fields describe optional contract checks.
|
|
32
|
+
``required=False`` marks a column that may be absent from the training frame;
|
|
33
|
+
``role="ignore"`` columns are always treated as optional.
|
|
32
34
|
"""
|
|
33
35
|
|
|
34
36
|
name: str
|
|
@@ -43,6 +45,7 @@ class ColumnSpec:
|
|
|
43
45
|
date_format: str | None = None
|
|
44
46
|
preserve_leading_zeros: bool = False
|
|
45
47
|
severity: Literal["error", "warning"] = "error"
|
|
48
|
+
required: bool = True
|
|
46
49
|
|
|
47
50
|
def __post_init__(self) -> None:
|
|
48
51
|
if not isinstance(self.name, str) or not self.name:
|
|
@@ -86,6 +89,7 @@ class ColumnSpec:
|
|
|
86
89
|
"date_format": self.date_format,
|
|
87
90
|
"preserve_leading_zeros": self.preserve_leading_zeros,
|
|
88
91
|
"severity": self.severity,
|
|
92
|
+
"required": self.required,
|
|
89
93
|
}
|
|
90
94
|
|
|
91
95
|
@classmethod
|
|
@@ -260,6 +264,8 @@ class DataContract:
|
|
|
260
264
|
if spec.role == "ignore":
|
|
261
265
|
continue
|
|
262
266
|
if spec.name not in frame.columns:
|
|
267
|
+
if not spec.required:
|
|
268
|
+
continue
|
|
263
269
|
findings.append(
|
|
264
270
|
self._finding(
|
|
265
271
|
spec,
|