menddata 0.1.0__py3-none-any.whl
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/__init__.py +133 -0
- MendData/audit.py +147 -0
- MendData/detectors.py +386 -0
- MendData/fixers.py +511 -0
- MendData/issue.py +236 -0
- MendData/scoring.py +229 -0
- MendData/session.py +502 -0
- MendData/utils.py +82 -0
- menddata-0.1.0.dist-info/METADATA +295 -0
- menddata-0.1.0.dist-info/RECORD +13 -0
- menddata-0.1.0.dist-info/WHEEL +5 -0
- menddata-0.1.0.dist-info/licenses/LICENSE +21 -0
- menddata-0.1.0.dist-info/top_level.txt +1 -0
MendData/issue.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""The ``Issue`` class: the shared contract between detectors and fixers.
|
|
2
|
+
|
|
3
|
+
Detectors create ``Issue`` objects, fixers read them, and ``CleaningSession``
|
|
4
|
+
passes them around. This module depends only on the standard library, so every
|
|
5
|
+
teammate can import it from day one.
|
|
6
|
+
|
|
7
|
+
Kinds of issue
|
|
8
|
+
``Issue.MISSING`` missing values in one column
|
|
9
|
+
``Issue.DUPLICATE`` repeated rows (row-level, so ``column`` is ``None``)
|
|
10
|
+
``Issue.OUTLIER`` extreme numeric values in one column
|
|
11
|
+
|
|
12
|
+
Severity
|
|
13
|
+
A float from 0 to 1: the share of what was checked that is affected.
|
|
14
|
+
Missing: missing cells / rows. Duplicate: duplicate rows / rows.
|
|
15
|
+
Outlier: outliers / non-missing values in the column. It is used for
|
|
16
|
+
ranking only and is not weighted across kinds.
|
|
17
|
+
|
|
18
|
+
Details (filled in by detectors, read by fixers)
|
|
19
|
+
missing no keys needed
|
|
20
|
+
duplicate ``subset``: list of column names, or ``None`` for all columns
|
|
21
|
+
outlier ``method`` ('iqr' or 'zscore'), plus the ``lower`` and
|
|
22
|
+
``upper`` bounds that were used to flag outliers
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import numbers
|
|
28
|
+
from collections.abc import Hashable, Mapping
|
|
29
|
+
from typing import Any, Optional
|
|
30
|
+
|
|
31
|
+
__all__ = ["Issue"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _plural(count: int, word: str) -> str:
|
|
35
|
+
"""Return ``word`` with an ``s`` added unless ``count`` is exactly 1."""
|
|
36
|
+
return word if count == 1 else word + "s"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Issue:
|
|
40
|
+
"""One data-quality problem found in a dataset.
|
|
41
|
+
|
|
42
|
+
An ``Issue`` is immutable: its values are stored in private attributes
|
|
43
|
+
and exposed through read-only properties, so nothing can change it after
|
|
44
|
+
it is created. Detectors build issues, ``CleaningSession`` ranks them,
|
|
45
|
+
and fixers read ``column``, ``kind`` and ``details`` to decide what to do.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
column: The column label (for example ``'age'``), or ``None`` for a
|
|
49
|
+
row-level issue. Only ``DUPLICATE`` issues may use ``None``.
|
|
50
|
+
kind: One of ``Issue.MISSING``, ``Issue.DUPLICATE`` or
|
|
51
|
+
``Issue.OUTLIER``.
|
|
52
|
+
count: How many values or rows are affected (0 or more). NumPy
|
|
53
|
+
integers are accepted and converted to ``int``.
|
|
54
|
+
severity: The share of what was checked that is affected, from 0 to
|
|
55
|
+
1. NumPy floats are accepted and converted to ``float``.
|
|
56
|
+
details: Optional mapping with extra facts for the fixer, such as
|
|
57
|
+
``{'method': 'iqr', 'lower': 1.0, 'upper': 9.0}``. It is copied.
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
TypeError: If an argument has the wrong type.
|
|
61
|
+
ValueError: If ``kind`` is unknown, ``column`` is ``None`` for a kind
|
|
62
|
+
that needs one, ``count`` is negative, or ``severity`` is outside
|
|
63
|
+
the range 0 to 1.
|
|
64
|
+
|
|
65
|
+
Example:
|
|
66
|
+
>>> issue = Issue('age', Issue.MISSING, count=12, severity=0.06)
|
|
67
|
+
>>> issue.describe()
|
|
68
|
+
"Column 'age' has 12 missing values (6.0% of its rows)."
|
|
69
|
+
>>> issue
|
|
70
|
+
Issue(column='age', kind='missing', count=12, severity=0.060)
|
|
71
|
+
>>> outlier = Issue('pay', Issue.OUTLIER, 3, 0.2,
|
|
72
|
+
... details={'method': 'iqr', 'lower': 1.0, 'upper': 9.0})
|
|
73
|
+
>>> [i.kind for i in sorted([issue, outlier], reverse=True)]
|
|
74
|
+
['outlier', 'missing']
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
MISSING = "missing"
|
|
78
|
+
DUPLICATE = "duplicate"
|
|
79
|
+
OUTLIER = "outlier"
|
|
80
|
+
KINDS = (MISSING, DUPLICATE, OUTLIER)
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
column: Optional[Hashable],
|
|
85
|
+
kind: str,
|
|
86
|
+
count: int,
|
|
87
|
+
severity: float,
|
|
88
|
+
details: Optional[Mapping[str, Any]] = None,
|
|
89
|
+
) -> None:
|
|
90
|
+
"""Validate the arguments and store them in private attributes.
|
|
91
|
+
|
|
92
|
+
See the class docstring for the meaning of each argument and for the
|
|
93
|
+
errors that can be raised.
|
|
94
|
+
"""
|
|
95
|
+
if not isinstance(kind, str):
|
|
96
|
+
raise TypeError(f"kind must be a string, got {type(kind).__name__}.")
|
|
97
|
+
if kind not in self.KINDS:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"kind must be one of {', '.join(self.KINDS)}; got {kind!r}."
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if column is None:
|
|
103
|
+
if kind != self.DUPLICATE:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"column is required for {kind!r} issues; "
|
|
106
|
+
"only 'duplicate' issues may use None."
|
|
107
|
+
)
|
|
108
|
+
elif not isinstance(column, Hashable):
|
|
109
|
+
raise TypeError("column must be a column label (such as a string) or None.")
|
|
110
|
+
|
|
111
|
+
if isinstance(count, bool) or not isinstance(count, numbers.Integral):
|
|
112
|
+
raise TypeError(f"count must be an integer, got {type(count).__name__}.")
|
|
113
|
+
if count < 0:
|
|
114
|
+
raise ValueError(f"count cannot be negative, got {count}.")
|
|
115
|
+
|
|
116
|
+
if isinstance(severity, bool) or not isinstance(severity, numbers.Real):
|
|
117
|
+
raise TypeError(
|
|
118
|
+
f"severity must be a number, got {type(severity).__name__}."
|
|
119
|
+
)
|
|
120
|
+
severity = float(severity)
|
|
121
|
+
if not 0.0 <= severity <= 1.0:
|
|
122
|
+
raise ValueError(f"severity must be between 0 and 1, got {severity}.")
|
|
123
|
+
|
|
124
|
+
if details is None:
|
|
125
|
+
details = {}
|
|
126
|
+
elif not isinstance(details, Mapping):
|
|
127
|
+
raise TypeError(
|
|
128
|
+
f"details must be a mapping or None, got {type(details).__name__}."
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
self._column = column
|
|
132
|
+
self._kind = kind
|
|
133
|
+
self._count = int(count)
|
|
134
|
+
self._severity = severity
|
|
135
|
+
self._details = dict(details)
|
|
136
|
+
|
|
137
|
+
# ------------------------------------------------------------------
|
|
138
|
+
# Read-only properties (encapsulation)
|
|
139
|
+
# ------------------------------------------------------------------
|
|
140
|
+
@property
|
|
141
|
+
def column(self) -> Optional[Hashable]:
|
|
142
|
+
"""The column label, or ``None`` for a row-level issue."""
|
|
143
|
+
return self._column
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def kind(self) -> str:
|
|
147
|
+
"""The kind of issue: ``'missing'``, ``'duplicate'`` or ``'outlier'``."""
|
|
148
|
+
return self._kind
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def count(self) -> int:
|
|
152
|
+
"""How many values or rows are affected."""
|
|
153
|
+
return self._count
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def severity(self) -> float:
|
|
157
|
+
"""The share of what was checked that is affected (0 to 1)."""
|
|
158
|
+
return self._severity
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def details(self) -> dict:
|
|
162
|
+
"""A copy of the extra facts the detector saved for the fixer."""
|
|
163
|
+
return dict(self._details)
|
|
164
|
+
|
|
165
|
+
# ------------------------------------------------------------------
|
|
166
|
+
# Plain-English description
|
|
167
|
+
# ------------------------------------------------------------------
|
|
168
|
+
def describe(self) -> str:
|
|
169
|
+
"""Describe the issue in one plain-English sentence.
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
A sentence such as ``"Column 'age' has 12 missing values (6.0% of
|
|
173
|
+
its rows)."``.
|
|
174
|
+
"""
|
|
175
|
+
pct = f"{self._severity:.1%}"
|
|
176
|
+
n = self._count
|
|
177
|
+
|
|
178
|
+
if self._kind == self.MISSING:
|
|
179
|
+
return (
|
|
180
|
+
f"Column '{self._column}' has {n} missing "
|
|
181
|
+
f"{_plural(n, 'value')} ({pct} of its rows)."
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
if self._kind == self.DUPLICATE:
|
|
185
|
+
sentence = f"Found {n} duplicate {_plural(n, 'row')} ({pct} of all rows)"
|
|
186
|
+
subset = self._details.get("subset")
|
|
187
|
+
if subset:
|
|
188
|
+
sentence += ", comparing only the columns " + ", ".join(
|
|
189
|
+
str(name) for name in subset
|
|
190
|
+
)
|
|
191
|
+
return sentence + "."
|
|
192
|
+
|
|
193
|
+
return (
|
|
194
|
+
f"Column '{self._column}' has {n} {_plural(n, 'outlier')} "
|
|
195
|
+
f"({pct} of its values)."
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
# ------------------------------------------------------------------
|
|
199
|
+
# Dunder methods (polymorphism through operator overloading)
|
|
200
|
+
# ------------------------------------------------------------------
|
|
201
|
+
def _key(self) -> tuple:
|
|
202
|
+
"""The fields that define equality and hashing (details are ignored)."""
|
|
203
|
+
return (self._column, self._kind, self._count, self._severity)
|
|
204
|
+
|
|
205
|
+
def __repr__(self) -> str:
|
|
206
|
+
"""Return a developer-friendly string (severity rounded to 3 places)."""
|
|
207
|
+
return (
|
|
208
|
+
f"Issue(column={self._column!r}, kind={self._kind!r}, "
|
|
209
|
+
f"count={self._count!r}, severity={self._severity:.3f})"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def __str__(self) -> str:
|
|
213
|
+
"""Return the plain-English description, so ``print(issue)`` is readable."""
|
|
214
|
+
return self.describe()
|
|
215
|
+
|
|
216
|
+
def __eq__(self, other: object) -> bool:
|
|
217
|
+
"""Two issues are equal if column, kind, count and severity match."""
|
|
218
|
+
if not isinstance(other, Issue):
|
|
219
|
+
return NotImplemented
|
|
220
|
+
return self._key() == other._key()
|
|
221
|
+
|
|
222
|
+
def __hash__(self) -> int:
|
|
223
|
+
"""Hash the same fields as ``__eq__`` so issues work in sets and dicts."""
|
|
224
|
+
return hash(self._key())
|
|
225
|
+
|
|
226
|
+
def __lt__(self, other: object) -> bool:
|
|
227
|
+
"""Compare by severity only, so issues can be ranked.
|
|
228
|
+
|
|
229
|
+
Python also uses this method for ``>``. ``<=`` and ``>=`` are
|
|
230
|
+
intentionally not supported: two different issues can share a
|
|
231
|
+
severity without being equal. Rank with
|
|
232
|
+
``sorted(issues, reverse=True)`` to put the worst issue first.
|
|
233
|
+
"""
|
|
234
|
+
if not isinstance(other, Issue):
|
|
235
|
+
return NotImplemented
|
|
236
|
+
return self._severity < other._severity
|
MendData/scoring.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Quality scoring module for MendData."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from math import isclose, isfinite
|
|
5
|
+
from numbers import Real
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class QualityScorer:
|
|
12
|
+
"""Calculate and compare dataset quality scores.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
weights (Mapping, optional): Custom weights for completeness,
|
|
16
|
+
uniqueness, and validity. Defaults to 0.4, 0.3, and 0.3.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
None
|
|
20
|
+
|
|
21
|
+
Raises:
|
|
22
|
+
TypeError: If weights is not a mapping.
|
|
23
|
+
ValueError: If weights are invalid or do not sum to 1.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, weights=None):
|
|
27
|
+
"""Initialize the scorer with default or custom weights.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
weights (Mapping, optional): Custom scoring weights.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
None
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
TypeError: If weights is not a mapping.
|
|
37
|
+
ValueError: If keys, values, or total weight are invalid.
|
|
38
|
+
"""
|
|
39
|
+
if weights is None:
|
|
40
|
+
weights = {
|
|
41
|
+
"completeness": 0.40,
|
|
42
|
+
"uniqueness": 0.30,
|
|
43
|
+
"validity": 0.30
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if not isinstance(weights, Mapping):
|
|
47
|
+
raise TypeError("Weights must be a mapping.")
|
|
48
|
+
|
|
49
|
+
required = {"completeness", "uniqueness", "validity"}
|
|
50
|
+
|
|
51
|
+
if set(weights.keys()) != required:
|
|
52
|
+
raise ValueError(
|
|
53
|
+
"Weights must contain completeness, uniqueness, and validity."
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
checked_weights = {}
|
|
57
|
+
|
|
58
|
+
for name, value in weights.items():
|
|
59
|
+
if (
|
|
60
|
+
isinstance(value, (bool, np.bool_))
|
|
61
|
+
or not isinstance(value, Real)
|
|
62
|
+
):
|
|
63
|
+
raise TypeError("Weights must be real numbers.")
|
|
64
|
+
|
|
65
|
+
if not isfinite(float(value)) or value < 0:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"Weights must be finite and non-negative."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
checked_weights[name] = float(value)
|
|
71
|
+
|
|
72
|
+
if not isclose(
|
|
73
|
+
sum(checked_weights.values()),
|
|
74
|
+
1.0,
|
|
75
|
+
rel_tol=0.0,
|
|
76
|
+
abs_tol=1e-9
|
|
77
|
+
):
|
|
78
|
+
raise ValueError("Weights must sum to 1.")
|
|
79
|
+
|
|
80
|
+
self._weights = checked_weights
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def weights(self):
|
|
84
|
+
"""Return a copy of the scoring weights.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
None
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
dict: A copy of the scoring weights.
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
None
|
|
94
|
+
"""
|
|
95
|
+
return self._weights.copy()
|
|
96
|
+
|
|
97
|
+
def breakdown(self, data):
|
|
98
|
+
"""Calculate completeness, uniqueness, and validity scores.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
data (pandas.DataFrame): Dataset to evaluate.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
dict: Three quality scores ranging from 0 to 100.
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
TypeError: If data is not a pandas DataFrame.
|
|
108
|
+
"""
|
|
109
|
+
if not isinstance(data, pd.DataFrame):
|
|
110
|
+
raise TypeError("Data must be a pandas DataFrame.")
|
|
111
|
+
|
|
112
|
+
if data.empty:
|
|
113
|
+
return {
|
|
114
|
+
"completeness": 0.0,
|
|
115
|
+
"uniqueness": 0.0,
|
|
116
|
+
"validity": 0.0,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
completeness = (
|
|
120
|
+
1 - data.isna().sum().sum() / data.size
|
|
121
|
+
) * 100
|
|
122
|
+
duplicate_count = data.duplicated().sum()
|
|
123
|
+
uniqueness = (
|
|
124
|
+
1 - duplicate_count / len(data)
|
|
125
|
+
) * 100
|
|
126
|
+
|
|
127
|
+
numeric_data = data.select_dtypes(
|
|
128
|
+
include="number", exclude=["bool", "boolean"]
|
|
129
|
+
)
|
|
130
|
+
valid_count = 0
|
|
131
|
+
total_count = 0
|
|
132
|
+
|
|
133
|
+
for column in numeric_data.columns:
|
|
134
|
+
values = numeric_data[column].dropna().astype(float)
|
|
135
|
+
if values.empty:
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
total_count += len(values)
|
|
139
|
+
finite_values = values[np.isfinite(values)]
|
|
140
|
+
if finite_values.empty:
|
|
141
|
+
continue
|
|
142
|
+
|
|
143
|
+
q1 = finite_values.quantile(0.25)
|
|
144
|
+
q3 = finite_values.quantile(0.75)
|
|
145
|
+
iqr = q3 - q1
|
|
146
|
+
|
|
147
|
+
if iqr == 0:
|
|
148
|
+
valid_count += len(finite_values)
|
|
149
|
+
continue
|
|
150
|
+
|
|
151
|
+
lower = q1 - 1.5 * iqr
|
|
152
|
+
upper = q3 + 1.5 * iqr
|
|
153
|
+
valid_count += (
|
|
154
|
+
(finite_values >= lower) & (finite_values <= upper)
|
|
155
|
+
).sum()
|
|
156
|
+
|
|
157
|
+
if total_count == 0:
|
|
158
|
+
validity = 100.0
|
|
159
|
+
else:
|
|
160
|
+
validity = (valid_count / total_count) * 100
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
"completeness": round(float(completeness), 2),
|
|
164
|
+
"uniqueness": round(float(uniqueness), 2),
|
|
165
|
+
"validity": round(float(validity), 2),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
def score(self, data):
|
|
169
|
+
"""Calculate the overall weighted quality score.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
data (pandas.DataFrame): Dataset to evaluate.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
float: Overall quality score rounded to 1 decimal place.
|
|
176
|
+
|
|
177
|
+
Raises:
|
|
178
|
+
TypeError: If data is not a pandas DataFrame.
|
|
179
|
+
"""
|
|
180
|
+
if not isinstance(data, pd.DataFrame):
|
|
181
|
+
raise TypeError("Data must be a pandas DataFrame.")
|
|
182
|
+
|
|
183
|
+
if data.empty:
|
|
184
|
+
return 0.0
|
|
185
|
+
|
|
186
|
+
parts = self.breakdown(data)
|
|
187
|
+
|
|
188
|
+
total = sum(
|
|
189
|
+
parts[name] * self._weights[name]
|
|
190
|
+
for name in self._weights
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
return round(float(total), 1)
|
|
194
|
+
|
|
195
|
+
def compare(self, before, after):
|
|
196
|
+
"""Compare dataset quality before and after cleaning.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
before (pandas.DataFrame): Original dataset.
|
|
200
|
+
after (pandas.DataFrame): Cleaned dataset.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
dict: Before score, after score, and score change.
|
|
204
|
+
|
|
205
|
+
Raises:
|
|
206
|
+
TypeError: If either input is not a DataFrame.
|
|
207
|
+
"""
|
|
208
|
+
before_score = self.score(before)
|
|
209
|
+
after_score = self.score(after)
|
|
210
|
+
return {
|
|
211
|
+
"before": before_score,
|
|
212
|
+
"after": after_score,
|
|
213
|
+
"change": round(after_score - before_score, 1) + 0.0,
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def __repr__(self):
|
|
218
|
+
"""Return a readable representation of the scorer.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
None
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
str: Representation of the QualityScorer object.
|
|
225
|
+
|
|
226
|
+
Raises:
|
|
227
|
+
None
|
|
228
|
+
"""
|
|
229
|
+
return f"QualityScorer(weights={self._weights})"
|