menddata 0.1.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.
- menddata-0.1.0/LICENSE +21 -0
- menddata-0.1.0/MendData/__init__.py +133 -0
- menddata-0.1.0/MendData/audit.py +147 -0
- menddata-0.1.0/MendData/detectors.py +386 -0
- menddata-0.1.0/MendData/fixers.py +511 -0
- menddata-0.1.0/MendData/issue.py +236 -0
- menddata-0.1.0/MendData/scoring.py +229 -0
- menddata-0.1.0/MendData/session.py +502 -0
- menddata-0.1.0/MendData/utils.py +82 -0
- menddata-0.1.0/PKG-INFO +295 -0
- menddata-0.1.0/README.md +262 -0
- menddata-0.1.0/menddata.egg-info/PKG-INFO +295 -0
- menddata-0.1.0/menddata.egg-info/SOURCES.txt +22 -0
- menddata-0.1.0/menddata.egg-info/dependency_links.txt +1 -0
- menddata-0.1.0/menddata.egg-info/requires.txt +5 -0
- menddata-0.1.0/menddata.egg-info/top_level.txt +1 -0
- menddata-0.1.0/setup.cfg +4 -0
- menddata-0.1.0/setup.py +39 -0
- menddata-0.1.0/tests/test_audit.py +129 -0
- menddata-0.1.0/tests/test_detectors.py +217 -0
- menddata-0.1.0/tests/test_fixers.py +513 -0
- menddata-0.1.0/tests/test_issue.py +356 -0
- menddata-0.1.0/tests/test_scoring.py +170 -0
- menddata-0.1.0/tests/test_session.py +406 -0
menddata-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ana Lynica B. Ferolino
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""MendData: a beginner-friendly data cleaning library for pandas.
|
|
2
|
+
|
|
3
|
+
MendData follows one simple order of work: scan a DataFrame for problems,
|
|
4
|
+
fix each one with a chosen strategy, score the quality before and after, and
|
|
5
|
+
explain every change in plain English.
|
|
6
|
+
|
|
7
|
+
Quick start
|
|
8
|
+
-----------
|
|
9
|
+
Wrap a DataFrame in a ``CleaningSession`` and call its methods. The methods
|
|
10
|
+
return values and never print, so wrap them in ``print()`` to see them::
|
|
11
|
+
|
|
12
|
+
import pandas as pd
|
|
13
|
+
from MendData import CleaningSession, ImputeFixer
|
|
14
|
+
|
|
15
|
+
df = pd.read_csv("messy_data.csv")
|
|
16
|
+
|
|
17
|
+
session = CleaningSession(df) # wrap a pandas DataFrame
|
|
18
|
+
session.scan() # find issues, ranked by severity
|
|
19
|
+
session.fix_all() # apply a default fixer to each issue
|
|
20
|
+
print(session.score()) # quality score before and after
|
|
21
|
+
print(session.report()) # plain-English summary of changes
|
|
22
|
+
session.undo() # revert the last cleaning step
|
|
23
|
+
session.reset() # go back to the original data
|
|
24
|
+
|
|
25
|
+
clean_df = session.data # a copy of the current data
|
|
26
|
+
|
|
27
|
+
To choose a strategy for one kind of issue, pass your own fixer::
|
|
28
|
+
|
|
29
|
+
session.fix_all(fixers={"missing": ImputeFixer("mean")})
|
|
30
|
+
|
|
31
|
+
Public classes
|
|
32
|
+
--------------
|
|
33
|
+
Issue
|
|
34
|
+
A problem found in the data (column, kind, count, severity, details).
|
|
35
|
+
BaseDetector, MissingValueDetector, DuplicateDetector, OutlierDetector
|
|
36
|
+
Find problems and return them as ``Issue`` objects.
|
|
37
|
+
BaseFixer, ImputeFixer, DropFixer, ClipFixer
|
|
38
|
+
Resolve an ``Issue`` using a chosen strategy.
|
|
39
|
+
QualityScorer
|
|
40
|
+
Rates a dataset from 0 to 100 (completeness, uniqueness, validity).
|
|
41
|
+
AuditLog
|
|
42
|
+
Records what each cleaning step did and why.
|
|
43
|
+
CleaningSession
|
|
44
|
+
The main entry point that ties all of the above together.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
import importlib
|
|
48
|
+
from typing import TYPE_CHECKING
|
|
49
|
+
|
|
50
|
+
# Package metadata. Keep __version__ and __license__ in sync with setup.py
|
|
51
|
+
# and the LICENSE file. TestPyPI/PyPI reject re-uploads of the same version,
|
|
52
|
+
# so bump __version__ before every new upload.
|
|
53
|
+
__version__ = "0.1.0"
|
|
54
|
+
__author__ = (
|
|
55
|
+
"Group 4 (DS2C): Ana Lynica B. Ferolino, Angeline B. Coniendo, "
|
|
56
|
+
"Joner D. Jusol, Janel P. Obrador"
|
|
57
|
+
)
|
|
58
|
+
__license__ = "MIT"
|
|
59
|
+
__url__ = "https://github.com/yninika/MendData"
|
|
60
|
+
|
|
61
|
+
# Every public name and the submodule that defines it. This is the single
|
|
62
|
+
# source of truth: to export a new class, add it here (and to the
|
|
63
|
+
# TYPE_CHECKING block below so editors can see it).
|
|
64
|
+
_EXPORTS = {
|
|
65
|
+
# Data model
|
|
66
|
+
"Issue": "issue",
|
|
67
|
+
# Detectors
|
|
68
|
+
"BaseDetector": "detectors",
|
|
69
|
+
"MissingValueDetector": "detectors",
|
|
70
|
+
"DuplicateDetector": "detectors",
|
|
71
|
+
"OutlierDetector": "detectors",
|
|
72
|
+
# Fixers
|
|
73
|
+
"BaseFixer": "fixers",
|
|
74
|
+
"ImputeFixer": "fixers",
|
|
75
|
+
"DropFixer": "fixers",
|
|
76
|
+
"ClipFixer": "fixers",
|
|
77
|
+
# Scoring and audit
|
|
78
|
+
"QualityScorer": "scoring",
|
|
79
|
+
"AuditLog": "audit",
|
|
80
|
+
# Main entry point
|
|
81
|
+
"CleaningSession": "session",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
__all__ = ["__version__"] + list(_EXPORTS)
|
|
85
|
+
|
|
86
|
+
# Never executed at runtime. It only lets editors, type checkers and
|
|
87
|
+
# documentation tools see where each public name comes from.
|
|
88
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
89
|
+
from .issue import Issue # noqa: F401
|
|
90
|
+
from .detectors import ( # noqa: F401
|
|
91
|
+
BaseDetector,
|
|
92
|
+
MissingValueDetector,
|
|
93
|
+
DuplicateDetector,
|
|
94
|
+
OutlierDetector,
|
|
95
|
+
)
|
|
96
|
+
from .fixers import BaseFixer, ImputeFixer, DropFixer, ClipFixer # noqa: F401
|
|
97
|
+
from .scoring import QualityScorer # noqa: F401
|
|
98
|
+
from .audit import AuditLog # noqa: F401
|
|
99
|
+
from .session import CleaningSession # noqa: F401
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def __getattr__(name: str):
|
|
103
|
+
"""Import a public class the first time it is asked for (PEP 562).
|
|
104
|
+
|
|
105
|
+
Because each submodule is only loaded when its classes are used,
|
|
106
|
+
``from MendData.detectors import MissingValueDetector`` works even while
|
|
107
|
+
teammates are still writing the other modules, and
|
|
108
|
+
``from MendData import CleaningSession`` works as soon as ``session.py``
|
|
109
|
+
and the modules it needs exist.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
name: The attribute being looked up on the package.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
The class called ``name``.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
AttributeError: If ``name`` is not a public MendData name.
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
module_name = _EXPORTS[name]
|
|
122
|
+
except KeyError:
|
|
123
|
+
raise AttributeError(
|
|
124
|
+
f"module {__name__!r} has no attribute {name!r}"
|
|
125
|
+
) from None
|
|
126
|
+
value = getattr(importlib.import_module(f".{module_name}", __name__), name)
|
|
127
|
+
globals()[name] = value # cache it so this function runs once per name
|
|
128
|
+
return value
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def __dir__() -> list:
|
|
132
|
+
"""List the public names so ``dir(MendData)`` and tab completion work."""
|
|
133
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Audit logging module for MendData."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from numbers import Integral
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AuditLog:
|
|
9
|
+
"""Record and export dataset cleaning activities.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
None
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
None
|
|
16
|
+
|
|
17
|
+
Raises:
|
|
18
|
+
None
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self):
|
|
22
|
+
"""Create an empty audit log.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
None
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
None
|
|
29
|
+
|
|
30
|
+
Raises:
|
|
31
|
+
None
|
|
32
|
+
"""
|
|
33
|
+
self._entries = []
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def entries(self):
|
|
37
|
+
"""Return a copy of the audit records.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
None
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
list: Copies of all recorded audit entries.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
None
|
|
47
|
+
"""
|
|
48
|
+
return [entry.copy() for entry in self._entries]
|
|
49
|
+
|
|
50
|
+
def record(self, step, reason, affected=0):
|
|
51
|
+
"""Record a dataset cleaning activity.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
step (str): Description of the cleaning step.
|
|
55
|
+
reason (str): Reason for performing the step.
|
|
56
|
+
affected (int): Number of affected rows or cells.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
None
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
TypeError: If step or reason is not a string, or if affected is not an integer.
|
|
63
|
+
ValueError: If step or reason is empty, or if affected is negative.
|
|
64
|
+
"""
|
|
65
|
+
if not isinstance(step, str):
|
|
66
|
+
raise TypeError("Step must be a string.")
|
|
67
|
+
if not step.strip():
|
|
68
|
+
raise ValueError("Step cannot be empty.")
|
|
69
|
+
if not isinstance(reason, str):
|
|
70
|
+
raise TypeError("Reason must be a string.")
|
|
71
|
+
if not reason.strip():
|
|
72
|
+
raise ValueError("Reason cannot be empty.")
|
|
73
|
+
if isinstance(affected, bool) or not isinstance(affected, Integral):
|
|
74
|
+
raise TypeError("Affected must be a non-negative integer.")
|
|
75
|
+
if affected < 0:
|
|
76
|
+
raise ValueError("Affected cannot be negative.")
|
|
77
|
+
|
|
78
|
+
timestamp = datetime.now().astimezone().isoformat()
|
|
79
|
+
self._entries.append(
|
|
80
|
+
{
|
|
81
|
+
"timestamp": timestamp,
|
|
82
|
+
"step": step.strip(),
|
|
83
|
+
"reason": reason.strip(),
|
|
84
|
+
"affected": int(affected),
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def export(self, path=None):
|
|
89
|
+
"""Export the audit history as readable text.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
path (str or Path, optional): File path where the report will be saved.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
str: The audit history as readable text.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
TypeError: If path is provided and is not a string or Path.
|
|
99
|
+
OSError: If the report cannot be written to the given path.
|
|
100
|
+
"""
|
|
101
|
+
if path is not None and not isinstance(path, (str, Path)):
|
|
102
|
+
raise TypeError("Path must be a string, Path, or None.")
|
|
103
|
+
|
|
104
|
+
lines = ["MendData Cleaning History"]
|
|
105
|
+
if not self._entries:
|
|
106
|
+
lines.append("No cleaning activities recorded.")
|
|
107
|
+
else:
|
|
108
|
+
for number, entry in enumerate(self._entries, start=1):
|
|
109
|
+
lines.append(
|
|
110
|
+
f"{number}. {entry['step']}\n"
|
|
111
|
+
f" Timestamp: {entry['timestamp']}\n"
|
|
112
|
+
f" Reason: {entry['reason']}\n"
|
|
113
|
+
f" Affected: {entry['affected']}"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
report = "\n".join(lines)
|
|
117
|
+
if path is not None:
|
|
118
|
+
Path(path).write_text(report + "\n", encoding="utf-8")
|
|
119
|
+
return report
|
|
120
|
+
|
|
121
|
+
def __len__(self):
|
|
122
|
+
"""Return the number of recorded activities.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
None
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
int: Number of audit entries.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
None
|
|
132
|
+
"""
|
|
133
|
+
return len(self._entries)
|
|
134
|
+
|
|
135
|
+
def __repr__(self):
|
|
136
|
+
"""Return a readable representation of the audit log.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
None
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
str: Representation of the AuditLog object.
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
None
|
|
146
|
+
"""
|
|
147
|
+
return f"AuditLog(entries={len(self._entries)})"
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""Detectors for finding data-quality issues in pandas DataFrames.
|
|
2
|
+
|
|
3
|
+
This module defines ``BaseDetector`` and three concrete subclasses:
|
|
4
|
+
``MissingValueDetector``, ``DuplicateDetector``, and ``OutlierDetector``.
|
|
5
|
+
Each detector reads a DataFrame without mutating it and returns ``Issue``
|
|
6
|
+
objects whose severity is at least ``min_severity``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
from collections.abc import Iterable
|
|
13
|
+
from typing import Any, Optional
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
from .issue import Issue
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"BaseDetector",
|
|
22
|
+
"MissingValueDetector",
|
|
23
|
+
"DuplicateDetector",
|
|
24
|
+
"OutlierDetector",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _validate_dataframe(data: Any) -> pd.DataFrame:
|
|
29
|
+
"""Validate that ``data`` is a pandas DataFrame."""
|
|
30
|
+
if not isinstance(data, pd.DataFrame):
|
|
31
|
+
raise TypeError(
|
|
32
|
+
f"data must be a pandas DataFrame, got {type(data).__name__}."
|
|
33
|
+
)
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _validate_severity(value: Any, name: str = "min_severity") -> float:
|
|
38
|
+
"""Validate that ``value`` is a real number (not bool) in [0.0, 1.0]."""
|
|
39
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, np.number)):
|
|
40
|
+
raise TypeError(
|
|
41
|
+
f"{name} must be a number between 0 and 1, got {type(value).__name__}."
|
|
42
|
+
)
|
|
43
|
+
number = float(value)
|
|
44
|
+
if np.isnan(number) or not (0.0 <= number <= 1.0):
|
|
45
|
+
raise ValueError(f"{name} must be between 0 and 1, got {value}.")
|
|
46
|
+
return number
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _validate_positive_threshold(value: Any, name: str = "threshold") -> float:
|
|
50
|
+
"""Validate that ``value`` is a positive real number (not bool)."""
|
|
51
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, np.number)):
|
|
52
|
+
raise TypeError(
|
|
53
|
+
f"{name} must be a positive number, got {type(value).__name__}."
|
|
54
|
+
)
|
|
55
|
+
number = float(value)
|
|
56
|
+
if np.isnan(number) or np.isinf(number) or number <= 0.0:
|
|
57
|
+
raise ValueError(f"{name} must be greater than 0, got {value}.")
|
|
58
|
+
return number
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class BaseDetector(ABC):
|
|
62
|
+
"""Abstract base class for DataFrame issue detectors.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
min_severity: Minimum severity threshold (from 0.0 to 1.0) required
|
|
66
|
+
for a detected ``Issue`` to be kept. Defaults to ``0.0``.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
TypeError: If ``min_severity`` is not a number.
|
|
70
|
+
ValueError: If ``min_severity`` is outside 0.0 to 1.0.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, min_severity: float = 0.0) -> None:
|
|
74
|
+
"""Initialize the detector with a minimum severity threshold."""
|
|
75
|
+
self._min_severity = _validate_severity(min_severity, "min_severity")
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def min_severity(self) -> float:
|
|
79
|
+
"""Minimum severity (from 0.0 to 1.0) for returned issues."""
|
|
80
|
+
return self._min_severity
|
|
81
|
+
|
|
82
|
+
def _prepare_data(self, data: Any) -> Optional[pd.DataFrame]:
|
|
83
|
+
"""Validate ``data`` and return ``None`` if it is empty."""
|
|
84
|
+
_validate_dataframe(data)
|
|
85
|
+
if data.empty:
|
|
86
|
+
return None
|
|
87
|
+
return data
|
|
88
|
+
|
|
89
|
+
def _filter_by_severity(self, issues: list[Issue]) -> list[Issue]:
|
|
90
|
+
"""Return only issues whose severity is at least ``min_severity``."""
|
|
91
|
+
return [
|
|
92
|
+
issue for issue in issues if issue.severity >= self._min_severity
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
@abstractmethod
|
|
96
|
+
def detect(self, data: pd.DataFrame) -> list[Issue]:
|
|
97
|
+
"""Scan ``data`` and return issues with severity >= ``min_severity``.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
data: The pandas DataFrame to inspect.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
A list of ``Issue`` objects meeting ``min_severity``. Returns an
|
|
104
|
+
empty list if ``data`` is empty or no qualifying issues are found.
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
TypeError: If ``data`` is not a pandas DataFrame.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class MissingValueDetector(BaseDetector):
|
|
112
|
+
"""Detect missing values in each column of a DataFrame.
|
|
113
|
+
|
|
114
|
+
Emits at most one ``Issue`` per column that contains missing values,
|
|
115
|
+
with severity equal to ``missing_count / len(data)``.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
min_severity: Minimum severity threshold (from 0.0 to 1.0).
|
|
119
|
+
Defaults to ``0.0``.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
def __init__(self, min_severity: float = 0.0) -> None:
|
|
123
|
+
"""Initialize the missing-value detector."""
|
|
124
|
+
super().__init__(min_severity=min_severity)
|
|
125
|
+
|
|
126
|
+
def detect(self, data: pd.DataFrame) -> list[Issue]:
|
|
127
|
+
"""Find columns with missing values and return qualifying issues.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
data: The pandas DataFrame to inspect.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
A list of ``Issue.MISSING`` items with severity >= ``min_severity``.
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
TypeError: If ``data`` is not a pandas DataFrame.
|
|
137
|
+
"""
|
|
138
|
+
prepared = self._prepare_data(data)
|
|
139
|
+
if prepared is None:
|
|
140
|
+
return []
|
|
141
|
+
|
|
142
|
+
total_rows = len(prepared)
|
|
143
|
+
issues: list[Issue] = []
|
|
144
|
+
|
|
145
|
+
for col in prepared.columns:
|
|
146
|
+
missing_count = int(prepared[col].isna().sum())
|
|
147
|
+
if missing_count > 0:
|
|
148
|
+
severity = float(missing_count) / float(total_rows)
|
|
149
|
+
issues.append(
|
|
150
|
+
Issue(
|
|
151
|
+
column=col,
|
|
152
|
+
kind=Issue.MISSING,
|
|
153
|
+
count=missing_count,
|
|
154
|
+
severity=severity,
|
|
155
|
+
details=None,
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return self._filter_by_severity(issues)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class DuplicateDetector(BaseDetector):
|
|
163
|
+
"""Detect duplicate rows in a DataFrame.
|
|
164
|
+
|
|
165
|
+
Emits at most one row-level ``Issue`` (``column=None``) when duplicate
|
|
166
|
+
rows exist, with severity equal to ``duplicate_count / len(data)`` and
|
|
167
|
+
``details={'subset': ...}``.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
subset: Optional iterable of column names to check for duplicates.
|
|
171
|
+
If ``None``, all columns are checked.
|
|
172
|
+
min_severity: Minimum severity threshold (from 0.0 to 1.0).
|
|
173
|
+
Defaults to ``0.0``.
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
TypeError: If ``subset`` is neither ``None`` nor an iterable of
|
|
177
|
+
column labels, or if ``min_severity`` is invalid.
|
|
178
|
+
ValueError: If ``min_severity`` is out of range, or if a column in
|
|
179
|
+
``subset`` is missing from ``data.columns`` when ``detect()`` runs.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
def __init__(
|
|
183
|
+
self,
|
|
184
|
+
subset: Optional[Iterable[Any]] = None,
|
|
185
|
+
min_severity: float = 0.0,
|
|
186
|
+
) -> None:
|
|
187
|
+
"""Initialize the duplicate-row detector."""
|
|
188
|
+
super().__init__(min_severity=min_severity)
|
|
189
|
+
if subset is None:
|
|
190
|
+
self._subset: Optional[list[Any]] = None
|
|
191
|
+
else:
|
|
192
|
+
if isinstance(subset, (str, bytes)) or not isinstance(subset, Iterable):
|
|
193
|
+
raise TypeError(
|
|
194
|
+
"subset must be None or an iterable of column names, "
|
|
195
|
+
f"got {type(subset).__name__}."
|
|
196
|
+
)
|
|
197
|
+
self._subset = list(subset)
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def subset(self) -> Optional[list[Any]]:
|
|
201
|
+
"""A copy of the column subset used for duplicate checks, or ``None``."""
|
|
202
|
+
if self._subset is None:
|
|
203
|
+
return None
|
|
204
|
+
return list(self._subset)
|
|
205
|
+
|
|
206
|
+
def detect(self, data: pd.DataFrame) -> list[Issue]:
|
|
207
|
+
"""Find duplicate rows and return a qualifying ``Issue.DUPLICATE``.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
data: The pandas DataFrame to inspect.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
A list containing at most one ``Issue.DUPLICATE`` item meeting
|
|
214
|
+
``min_severity``.
|
|
215
|
+
|
|
216
|
+
Raises:
|
|
217
|
+
TypeError: If ``data`` is not a pandas DataFrame.
|
|
218
|
+
ValueError: If any column in ``subset`` is not in ``data.columns``.
|
|
219
|
+
"""
|
|
220
|
+
prepared = self._prepare_data(data)
|
|
221
|
+
if prepared is None:
|
|
222
|
+
return []
|
|
223
|
+
|
|
224
|
+
subset_copy = self.subset
|
|
225
|
+
if subset_copy is not None:
|
|
226
|
+
missing_cols = [
|
|
227
|
+
col for col in subset_copy if col not in prepared.columns
|
|
228
|
+
]
|
|
229
|
+
if missing_cols:
|
|
230
|
+
raise ValueError(
|
|
231
|
+
"subset contains unknown column(s): "
|
|
232
|
+
+ ", ".join(repr(col) for col in missing_cols)
|
|
233
|
+
+ "."
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
dup_count = int(prepared.duplicated(subset=subset_copy).sum())
|
|
237
|
+
if dup_count == 0:
|
|
238
|
+
return []
|
|
239
|
+
|
|
240
|
+
severity = float(dup_count) / float(len(prepared))
|
|
241
|
+
issues = [
|
|
242
|
+
Issue(
|
|
243
|
+
column=None,
|
|
244
|
+
kind=Issue.DUPLICATE,
|
|
245
|
+
count=dup_count,
|
|
246
|
+
severity=severity,
|
|
247
|
+
details={"subset": subset_copy},
|
|
248
|
+
)
|
|
249
|
+
]
|
|
250
|
+
return self._filter_by_severity(issues)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class OutlierDetector(BaseDetector):
|
|
254
|
+
"""Detect numeric outliers in each column using IQR or z-score fences.
|
|
255
|
+
|
|
256
|
+
Inspects numeric columns only (excluding booleans), ignores missing
|
|
257
|
+
values, and skips columns with fewer than 4 non-missing values or zero
|
|
258
|
+
spread. Emits at most one ``Issue.OUTLIER`` per qualifying column with
|
|
259
|
+
``details={'method': ..., 'lower': float, 'upper': float}``.
|
|
260
|
+
|
|
261
|
+
Args:
|
|
262
|
+
method: Outlier detection method: ``'iqr'`` or ``'zscore'``.
|
|
263
|
+
Defaults to ``'iqr'``.
|
|
264
|
+
threshold: Multiplier ``k`` for bounds. Defaults to ``1.5`` for
|
|
265
|
+
``'iqr'`` and ``3.0`` for ``'zscore'``.
|
|
266
|
+
min_severity: Minimum severity threshold (from 0.0 to 1.0).
|
|
267
|
+
Defaults to ``0.0``.
|
|
268
|
+
|
|
269
|
+
Raises:
|
|
270
|
+
TypeError: If an argument has an invalid type.
|
|
271
|
+
ValueError: If ``method`` is unsupported, ``threshold`` is not
|
|
272
|
+
positive, or ``min_severity`` is outside 0.0 to 1.0.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
VALID_METHODS = ("iqr", "zscore")
|
|
276
|
+
DEFAULT_THRESHOLDS = {"iqr": 1.5, "zscore": 3.0}
|
|
277
|
+
MIN_NON_MISSING = 4
|
|
278
|
+
|
|
279
|
+
def __init__(
|
|
280
|
+
self,
|
|
281
|
+
method: str = "iqr",
|
|
282
|
+
threshold: Optional[float] = None,
|
|
283
|
+
min_severity: float = 0.0,
|
|
284
|
+
) -> None:
|
|
285
|
+
"""Initialize the outlier detector."""
|
|
286
|
+
super().__init__(min_severity=min_severity)
|
|
287
|
+
if not isinstance(method, str):
|
|
288
|
+
raise TypeError(f"method must be a string, got {type(method).__name__}.")
|
|
289
|
+
if method not in self.VALID_METHODS:
|
|
290
|
+
raise ValueError(
|
|
291
|
+
f"method must be one of 'iqr' or 'zscore', got {method!r}."
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
resolved_threshold = (
|
|
295
|
+
self.DEFAULT_THRESHOLDS[method] if threshold is None else threshold
|
|
296
|
+
)
|
|
297
|
+
self._method = method
|
|
298
|
+
self._threshold = _validate_positive_threshold(resolved_threshold, "threshold")
|
|
299
|
+
|
|
300
|
+
@property
|
|
301
|
+
def method(self) -> str:
|
|
302
|
+
"""Outlier detection method (``'iqr'`` or ``'zscore'``)."""
|
|
303
|
+
return self._method
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def threshold(self) -> float:
|
|
307
|
+
"""Positive multiplier ``k`` used to compute lower and upper bounds."""
|
|
308
|
+
return self._threshold
|
|
309
|
+
|
|
310
|
+
def _compute_bounds(self, series: pd.Series) -> Optional[tuple[float, float]]:
|
|
311
|
+
"""Compute ``(lower, upper)`` bounds for a non-empty numeric Series.
|
|
312
|
+
|
|
313
|
+
Returns ``None`` if the column has fewer than 4 non-missing values
|
|
314
|
+
or zero spread.
|
|
315
|
+
"""
|
|
316
|
+
clean = series.dropna().astype(float)
|
|
317
|
+
if len(clean) < self.MIN_NON_MISSING:
|
|
318
|
+
return None
|
|
319
|
+
|
|
320
|
+
if self._method == "iqr":
|
|
321
|
+
q1 = float(np.percentile(clean, 25))
|
|
322
|
+
q3 = float(np.percentile(clean, 75))
|
|
323
|
+
iqr = q3 - q1
|
|
324
|
+
if iqr == 0.0:
|
|
325
|
+
return None
|
|
326
|
+
lower = q1 - self._threshold * iqr
|
|
327
|
+
upper = q3 + self._threshold * iqr
|
|
328
|
+
return (float(lower), float(upper))
|
|
329
|
+
|
|
330
|
+
mean_val = float(clean.mean())
|
|
331
|
+
std_val = float(clean.std(ddof=1))
|
|
332
|
+
if std_val == 0.0 or np.isnan(std_val):
|
|
333
|
+
return None
|
|
334
|
+
lower = mean_val - self._threshold * std_val
|
|
335
|
+
upper = mean_val + self._threshold * std_val
|
|
336
|
+
return (float(lower), float(upper))
|
|
337
|
+
|
|
338
|
+
def detect(self, data: pd.DataFrame) -> list[Issue]:
|
|
339
|
+
"""Find numeric column outliers and return qualifying issues.
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
data: The pandas DataFrame to inspect.
|
|
343
|
+
|
|
344
|
+
Returns:
|
|
345
|
+
A list of ``Issue.OUTLIER`` items with severity >= ``min_severity``.
|
|
346
|
+
|
|
347
|
+
Raises:
|
|
348
|
+
TypeError: If ``data`` is not a pandas DataFrame.
|
|
349
|
+
"""
|
|
350
|
+
prepared = self._prepare_data(data)
|
|
351
|
+
if prepared is None:
|
|
352
|
+
return []
|
|
353
|
+
|
|
354
|
+
numeric_cols = prepared.select_dtypes(
|
|
355
|
+
include=[np.number], exclude=[bool, "boolean"]
|
|
356
|
+
).columns
|
|
357
|
+
issues: list[Issue] = []
|
|
358
|
+
|
|
359
|
+
for col in numeric_cols:
|
|
360
|
+
bounds = self._compute_bounds(prepared[col])
|
|
361
|
+
if bounds is None:
|
|
362
|
+
continue
|
|
363
|
+
|
|
364
|
+
lower, upper = bounds
|
|
365
|
+
non_null = prepared[col].dropna().astype(float)
|
|
366
|
+
non_null_count = len(non_null)
|
|
367
|
+
outlier_mask = (non_null < lower) | (non_null > upper)
|
|
368
|
+
outlier_count = int(outlier_mask.sum())
|
|
369
|
+
|
|
370
|
+
if outlier_count > 0:
|
|
371
|
+
severity = float(outlier_count) / float(non_null_count)
|
|
372
|
+
issues.append(
|
|
373
|
+
Issue(
|
|
374
|
+
column=col,
|
|
375
|
+
kind=Issue.OUTLIER,
|
|
376
|
+
count=outlier_count,
|
|
377
|
+
severity=severity,
|
|
378
|
+
details={
|
|
379
|
+
"method": self._method,
|
|
380
|
+
"lower": lower,
|
|
381
|
+
"upper": upper,
|
|
382
|
+
},
|
|
383
|
+
)
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
return self._filter_by_severity(issues)
|