missinglens 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.
- missinglens-0.1.0/LICENSE +21 -0
- missinglens-0.1.0/PKG-INFO +98 -0
- missinglens-0.1.0/README.md +66 -0
- missinglens-0.1.0/pyproject.toml +60 -0
- missinglens-0.1.0/setup.cfg +4 -0
- missinglens-0.1.0/src/missinglens/__init__.py +6 -0
- missinglens-0.1.0/src/missinglens/analyzer.py +105 -0
- missinglens-0.1.0/src/missinglens/apply.py +99 -0
- missinglens-0.1.0/src/missinglens/cli.py +32 -0
- missinglens-0.1.0/src/missinglens/config.py +44 -0
- missinglens-0.1.0/src/missinglens/patterns.py +379 -0
- missinglens-0.1.0/src/missinglens/recommender.py +273 -0
- missinglens-0.1.0/src/missinglens/report.py +230 -0
- missinglens-0.1.0/src/missinglens.egg-info/PKG-INFO +98 -0
- missinglens-0.1.0/src/missinglens.egg-info/SOURCES.txt +23 -0
- missinglens-0.1.0/src/missinglens.egg-info/dependency_links.txt +1 -0
- missinglens-0.1.0/src/missinglens.egg-info/entry_points.txt +2 -0
- missinglens-0.1.0/src/missinglens.egg-info/requires.txt +14 -0
- missinglens-0.1.0/src/missinglens.egg-info/top_level.txt +1 -0
- missinglens-0.1.0/tests/test_analyzer.py +50 -0
- missinglens-0.1.0/tests/test_patterns.py +78 -0
- missinglens-0.1.0/tests/test_recommender.py +71 -0
- missinglens-0.1.0/tests/test_report_apply_cli.py +58 -0
- missinglens-0.1.0/tests/test_synthetic_and_datasets.py +22 -0
- missinglens-0.1.0/tests/test_validation.py +250 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 missinglens contributors
|
|
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,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: missinglens
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Analyze missing data per column: missingness rate, pattern detection, dtype-aware recommendations, and safe imputation.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/ab-rar-6024/missinglens
|
|
7
|
+
Project-URL: Repository, https://github.com/ab-rar-6024/missinglens
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: pandas>=2.0
|
|
20
|
+
Requires-Dist: numpy>=1.24
|
|
21
|
+
Requires-Dist: scipy>=1.10
|
|
22
|
+
Requires-Dist: scikit-learn>=1.3
|
|
23
|
+
Requires-Dist: typer>=0.9
|
|
24
|
+
Provides-Extra: plot
|
|
25
|
+
Requires-Dist: matplotlib>=3.7; extra == "plot"
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
28
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
29
|
+
Requires-Dist: matplotlib>=3.7; extra == "dev"
|
|
30
|
+
Requires-Dist: psutil>=5.9; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# missinglens
|
|
34
|
+
|
|
35
|
+
Analyze missing data per column: how much is missing, what pattern the missingness follows, and what to do about it for that column's dtype.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install missinglens
|
|
41
|
+
# Optional plotting support:
|
|
42
|
+
pip install "missinglens[plot]"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import missinglens as ml
|
|
49
|
+
|
|
50
|
+
report = ml.analyze(df, time_col="date") # time_col optional
|
|
51
|
+
print(report.summary())
|
|
52
|
+
print(report.explain("income"))
|
|
53
|
+
report.to_html("report.html")
|
|
54
|
+
df_clean, log = report.apply() # does not mutate input df
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
CLI:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
missinglens data.csv --time-col date --out report.html
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Supported Patterns
|
|
64
|
+
|
|
65
|
+
| Pattern | Detection Method | Default Recommendation (Numeric) |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `TREND` | Spearman correlation over adaptive time/row buckets | `interpolate` |
|
|
68
|
+
| `SEASONAL` | Chi-square across hour/weekday/month (`time_col` required) | `interpolate` |
|
|
69
|
+
| `BLOCK` | Run-length encoding vs Bernoulli null expectation | `interpolate_short_flag_long` |
|
|
70
|
+
| `MAR` | Mann-Whitney / Chi-square (BH-FDR) + shallow tree CV-AUC | `knn` (using driver columns) |
|
|
71
|
+
| `CO-MISSING` | Pearson correlation of missingness indicators | `iterative` |
|
|
72
|
+
| `MCAR` | Default when no structured pattern is significant | `mean` (symmetric) / `median` (skewed) |
|
|
73
|
+
|
|
74
|
+
## When to Trust the Verdict
|
|
75
|
+
|
|
76
|
+
- **High/Medium confidence (`missing_count >= 15`, `n >= 100`)**: Statistical tests have sufficient power; `MCAR` means no structured pattern was found despite adequate sample size.
|
|
77
|
+
- **Low confidence (`"no pattern detected (low power)"`)**: Triggered when `missing_count < 15` or `n < 100`. A lack of detected pattern here does **not** prove MCAR—treat the verdict as exploratory.
|
|
78
|
+
- **Domain semantics**: Real-world "not applicable" missingness (e.g., `PoolQC` in Ames Housing when a house has no pool) may appear as `MCAR` or `MAR` statistically; domain knowledge should override automated imputation.
|
|
79
|
+
|
|
80
|
+
## Calibration & Held-Out Evaluation
|
|
81
|
+
|
|
82
|
+
- Full 50-seed held-out evaluation (`n in {200, 1000, 10000}`, `rate in {0.02, 0.05, 0.10, 0.20}`) with 95% Wilson CIs is in [docs/evaluation.md](docs/evaluation.md).
|
|
83
|
+
- **`missingly` (`0.3.0`) Comparison** (10 held-out `n=1000, rate=0.20` datasets):
|
|
84
|
+
- `MAR` driven by a fully observed column: `missinglens` detected `10/10`; `missingly.mar_mnar_test(X, Y)` returned `[]` (`0/10`).
|
|
85
|
+
- `TREND`: `missinglens` detected `10/10`; `missingly.miss_ts_summary` reports gap counts/lengths only (no trend test).
|
|
86
|
+
- `SEASONAL`: `missinglens` detected `10/10`; `missingly` has no seasonal detector.
|
|
87
|
+
- **Performance (1M × 50)**: `31.99s`, `128.8 MB` tracemalloc peak (down from `260.38s` before 50k subsampling in `detect_mar`).
|
|
88
|
+
|
|
89
|
+
## Limitations
|
|
90
|
+
|
|
91
|
+
- `SEASONAL` detection requires `time_col` to be provided.
|
|
92
|
+
- `MNAR` cannot be proven from observed data alone; when suspected, use `flag_and_impute`.
|
|
93
|
+
- Low-sample regimes (`missing_count < 15` or `n < 100`) have low statistical power.
|
|
94
|
+
- `POWER_TABLE` was calibrated on synthetic trends and may overestimate power for weaker real-world trends.
|
|
95
|
+
- `TREND` is a significance test and may flag tiny effects at very large `n`.
|
|
96
|
+
- Patterns are chosen by fixed precedence (`BLOCK`, `TREND`, `SEASONAL`, `CO-MISSING`, `MAR`) and only the first is reported in `summary()`.
|
|
97
|
+
- All accuracy numbers come from synthetic data.
|
|
98
|
+
- In the fresh-seed evaluation (`3000..3049`, [docs/evaluation_final.md](docs/evaluation_final.md)), wrong-but-confident verdicts exceeded 5% in 3 regimes: `n=200, rate=0.20, MAR` (`3/50`, 6.0%), `n=200, rate=0.20, TREND` (`4/50`, 8.0%), and `n=10000, rate=0.10, CO-MISSING` (`6/100`, 6.0%).
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# missinglens
|
|
2
|
+
|
|
3
|
+
Analyze missing data per column: how much is missing, what pattern the missingness follows, and what to do about it for that column's dtype.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install missinglens
|
|
9
|
+
# Optional plotting support:
|
|
10
|
+
pip install "missinglens[plot]"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import missinglens as ml
|
|
17
|
+
|
|
18
|
+
report = ml.analyze(df, time_col="date") # time_col optional
|
|
19
|
+
print(report.summary())
|
|
20
|
+
print(report.explain("income"))
|
|
21
|
+
report.to_html("report.html")
|
|
22
|
+
df_clean, log = report.apply() # does not mutate input df
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
CLI:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
missinglens data.csv --time-col date --out report.html
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Supported Patterns
|
|
32
|
+
|
|
33
|
+
| Pattern | Detection Method | Default Recommendation (Numeric) |
|
|
34
|
+
| --- | --- | --- |
|
|
35
|
+
| `TREND` | Spearman correlation over adaptive time/row buckets | `interpolate` |
|
|
36
|
+
| `SEASONAL` | Chi-square across hour/weekday/month (`time_col` required) | `interpolate` |
|
|
37
|
+
| `BLOCK` | Run-length encoding vs Bernoulli null expectation | `interpolate_short_flag_long` |
|
|
38
|
+
| `MAR` | Mann-Whitney / Chi-square (BH-FDR) + shallow tree CV-AUC | `knn` (using driver columns) |
|
|
39
|
+
| `CO-MISSING` | Pearson correlation of missingness indicators | `iterative` |
|
|
40
|
+
| `MCAR` | Default when no structured pattern is significant | `mean` (symmetric) / `median` (skewed) |
|
|
41
|
+
|
|
42
|
+
## When to Trust the Verdict
|
|
43
|
+
|
|
44
|
+
- **High/Medium confidence (`missing_count >= 15`, `n >= 100`)**: Statistical tests have sufficient power; `MCAR` means no structured pattern was found despite adequate sample size.
|
|
45
|
+
- **Low confidence (`"no pattern detected (low power)"`)**: Triggered when `missing_count < 15` or `n < 100`. A lack of detected pattern here does **not** prove MCAR—treat the verdict as exploratory.
|
|
46
|
+
- **Domain semantics**: Real-world "not applicable" missingness (e.g., `PoolQC` in Ames Housing when a house has no pool) may appear as `MCAR` or `MAR` statistically; domain knowledge should override automated imputation.
|
|
47
|
+
|
|
48
|
+
## Calibration & Held-Out Evaluation
|
|
49
|
+
|
|
50
|
+
- Full 50-seed held-out evaluation (`n in {200, 1000, 10000}`, `rate in {0.02, 0.05, 0.10, 0.20}`) with 95% Wilson CIs is in [docs/evaluation.md](docs/evaluation.md).
|
|
51
|
+
- **`missingly` (`0.3.0`) Comparison** (10 held-out `n=1000, rate=0.20` datasets):
|
|
52
|
+
- `MAR` driven by a fully observed column: `missinglens` detected `10/10`; `missingly.mar_mnar_test(X, Y)` returned `[]` (`0/10`).
|
|
53
|
+
- `TREND`: `missinglens` detected `10/10`; `missingly.miss_ts_summary` reports gap counts/lengths only (no trend test).
|
|
54
|
+
- `SEASONAL`: `missinglens` detected `10/10`; `missingly` has no seasonal detector.
|
|
55
|
+
- **Performance (1M × 50)**: `31.99s`, `128.8 MB` tracemalloc peak (down from `260.38s` before 50k subsampling in `detect_mar`).
|
|
56
|
+
|
|
57
|
+
## Limitations
|
|
58
|
+
|
|
59
|
+
- `SEASONAL` detection requires `time_col` to be provided.
|
|
60
|
+
- `MNAR` cannot be proven from observed data alone; when suspected, use `flag_and_impute`.
|
|
61
|
+
- Low-sample regimes (`missing_count < 15` or `n < 100`) have low statistical power.
|
|
62
|
+
- `POWER_TABLE` was calibrated on synthetic trends and may overestimate power for weaker real-world trends.
|
|
63
|
+
- `TREND` is a significance test and may flag tiny effects at very large `n`.
|
|
64
|
+
- Patterns are chosen by fixed precedence (`BLOCK`, `TREND`, `SEASONAL`, `CO-MISSING`, `MAR`) and only the first is reported in `summary()`.
|
|
65
|
+
- All accuracy numbers come from synthetic data.
|
|
66
|
+
- In the fresh-seed evaluation (`3000..3049`, [docs/evaluation_final.md](docs/evaluation_final.md)), wrong-but-confident verdicts exceeded 5% in 3 regimes: `n=200, rate=0.20, MAR` (`3/50`, 6.0%), `n=200, rate=0.20, TREND` (`4/50`, 8.0%), and `n=10000, rate=0.10, CO-MISSING` (`6/100`, 6.0%).
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "missinglens"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Analyze missing data per column: missingness rate, pattern detection, dtype-aware recommendations, and safe imputation."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Intended Audience :: Science/Research",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.10",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Topic :: Scientific/Engineering",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
dependencies = [
|
|
24
|
+
"pandas>=2.0",
|
|
25
|
+
"numpy>=1.24",
|
|
26
|
+
"scipy>=1.10",
|
|
27
|
+
"scikit-learn>=1.3",
|
|
28
|
+
"typer>=0.9",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/ab-rar-6024/missinglens"
|
|
33
|
+
Repository = "https://github.com/ab-rar-6024/missinglens"
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
plot = ["matplotlib>=3.7"]
|
|
37
|
+
dev = [
|
|
38
|
+
"pytest>=7.4",
|
|
39
|
+
"ruff>=0.4",
|
|
40
|
+
"matplotlib>=3.7",
|
|
41
|
+
"psutil>=5.9",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[project.scripts]
|
|
45
|
+
missinglens = "missinglens.cli:app"
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.packages.find]
|
|
48
|
+
where = ["src"]
|
|
49
|
+
|
|
50
|
+
[tool.pytest.ini_options]
|
|
51
|
+
pythonpath = ["."]
|
|
52
|
+
testpaths = ["tests"]
|
|
53
|
+
addopts = "-q"
|
|
54
|
+
|
|
55
|
+
[tool.ruff]
|
|
56
|
+
line-length = 100
|
|
57
|
+
target-version = "py310"
|
|
58
|
+
|
|
59
|
+
[tool.ruff.lint]
|
|
60
|
+
select = ["E", "F", "I", "W"]
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Column-level missingness and dtype analysis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class ColumnInfo:
|
|
13
|
+
"""Summary metadata for a single DataFrame column."""
|
|
14
|
+
|
|
15
|
+
name: str
|
|
16
|
+
dtype_class: str # numeric | categorical | boolean | datetime | text/id
|
|
17
|
+
missing_count: int
|
|
18
|
+
total_count: int
|
|
19
|
+
missing_pct: float
|
|
20
|
+
is_constant: bool
|
|
21
|
+
is_symmetric: bool
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class AnalysisResult:
|
|
26
|
+
"""Result of analyzing all columns in a DataFrame."""
|
|
27
|
+
|
|
28
|
+
columns: dict[str, ColumnInfo]
|
|
29
|
+
indicator_matrix: pd.DataFrame
|
|
30
|
+
time_col: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _classify_dtype(series: pd.Series, name: str) -> str:
|
|
34
|
+
"""Classify a pandas Series into one of the five missinglens dtype classes."""
|
|
35
|
+
if pd.api.types.is_bool_dtype(series):
|
|
36
|
+
return "boolean"
|
|
37
|
+
if pd.api.types.is_datetime64_any_dtype(series):
|
|
38
|
+
return "datetime"
|
|
39
|
+
if pd.api.types.is_numeric_dtype(series):
|
|
40
|
+
return "numeric"
|
|
41
|
+
if isinstance(series.dtype, pd.CategoricalDtype):
|
|
42
|
+
return "categorical"
|
|
43
|
+
|
|
44
|
+
non_null = series.dropna()
|
|
45
|
+
if len(non_null) == 0:
|
|
46
|
+
return "text/id" if "id" in name.lower() else "categorical"
|
|
47
|
+
|
|
48
|
+
# Check if object column is actually boolean
|
|
49
|
+
unique_vals = set(non_null.unique())
|
|
50
|
+
if unique_vals.issubset({True, False, "True", "False", "true", "false"}):
|
|
51
|
+
return "boolean"
|
|
52
|
+
|
|
53
|
+
n_unique = non_null.nunique()
|
|
54
|
+
avg_len = non_null.astype(str).str.len().mean()
|
|
55
|
+
lower_name = name.lower()
|
|
56
|
+
if "id" in lower_name or (n_unique / max(len(non_null), 1) > 0.8 and len(non_null) > 10):
|
|
57
|
+
return "text/id"
|
|
58
|
+
if avg_len > 30:
|
|
59
|
+
return "text/id"
|
|
60
|
+
return "categorical"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check_symmetry(series: pd.Series, dtype_class: str) -> bool:
|
|
64
|
+
"""Return True if a numeric series is roughly symmetric (|skew| <= 0.5)."""
|
|
65
|
+
if dtype_class != "numeric":
|
|
66
|
+
return False
|
|
67
|
+
non_null = series.dropna()
|
|
68
|
+
if len(non_null) < 8 or non_null.nunique() <= 1:
|
|
69
|
+
return True
|
|
70
|
+
skew = float(non_null.skew())
|
|
71
|
+
return bool(np.isfinite(skew) and abs(skew) <= 0.5)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def analyze_columns(df: pd.DataFrame, time_col: str | None = None) -> AnalysisResult:
|
|
75
|
+
"""Analyze missingness, dtype class, and build the missing-indicator matrix."""
|
|
76
|
+
if df.empty or len(df.columns) == 0:
|
|
77
|
+
return AnalysisResult(
|
|
78
|
+
columns={},
|
|
79
|
+
indicator_matrix=pd.DataFrame(index=df.index),
|
|
80
|
+
time_col=time_col,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
indicator_matrix = df.isna().astype(np.int8)
|
|
84
|
+
total_count = len(df)
|
|
85
|
+
columns: dict[str, ColumnInfo] = {}
|
|
86
|
+
|
|
87
|
+
for col in df.columns:
|
|
88
|
+
s = df[col]
|
|
89
|
+
dtype_class = _classify_dtype(s, str(col))
|
|
90
|
+
missing_count = int(indicator_matrix[col].sum())
|
|
91
|
+
missing_pct = (missing_count / total_count * 100.0) if total_count > 0 else 0.0
|
|
92
|
+
non_null = s.dropna()
|
|
93
|
+
is_constant = non_null.nunique() <= 1
|
|
94
|
+
is_symmetric = _check_symmetry(s, dtype_class)
|
|
95
|
+
columns[str(col)] = ColumnInfo(
|
|
96
|
+
name=str(col),
|
|
97
|
+
dtype_class=dtype_class,
|
|
98
|
+
missing_count=missing_count,
|
|
99
|
+
total_count=total_count,
|
|
100
|
+
missing_pct=missing_pct,
|
|
101
|
+
is_constant=is_constant,
|
|
102
|
+
is_symmetric=is_symmetric,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
return AnalysisResult(columns=columns, indicator_matrix=indicator_matrix, time_col=time_col)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Apply missingness recommendations without mutating the input DataFrame."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from sklearn.experimental import enable_iterative_imputer # noqa: F401
|
|
7
|
+
from sklearn.impute import IterativeImputer, KNNImputer, SimpleImputer
|
|
8
|
+
|
|
9
|
+
from missinglens.config import DEFAULT_CONFIG, ThresholdConfig
|
|
10
|
+
from missinglens.recommender import Recommendation
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def apply_recommendations(
|
|
14
|
+
df: pd.DataFrame,
|
|
15
|
+
recommendations: dict[str, Recommendation],
|
|
16
|
+
time_col: str | None = None,
|
|
17
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
18
|
+
) -> tuple[pd.DataFrame, list[str]]:
|
|
19
|
+
"""Return (df_clean, log) after applying recommendations. Never mutates `df`."""
|
|
20
|
+
out = df.copy(deep=True)
|
|
21
|
+
log: list[str] = []
|
|
22
|
+
|
|
23
|
+
numeric_cols = [c for c in out.columns if pd.api.types.is_numeric_dtype(out[c])]
|
|
24
|
+
|
|
25
|
+
for col, rec in recommendations.items():
|
|
26
|
+
if col not in out.columns or rec.method in ("none", "do_not_impute"):
|
|
27
|
+
continue
|
|
28
|
+
|
|
29
|
+
if rec.method == "drop_column":
|
|
30
|
+
out = out.drop(columns=[col])
|
|
31
|
+
log.append(f"Dropped '{col}' ({rec.reason})")
|
|
32
|
+
continue
|
|
33
|
+
|
|
34
|
+
if rec.method == "mean":
|
|
35
|
+
imp = SimpleImputer(strategy="mean")
|
|
36
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
37
|
+
log.append(f"Imputed '{col}' with mean.")
|
|
38
|
+
elif rec.method == "median":
|
|
39
|
+
imp = SimpleImputer(strategy="median")
|
|
40
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
41
|
+
log.append(f"Imputed '{col}' with median.")
|
|
42
|
+
elif rec.method == "mode":
|
|
43
|
+
imp = SimpleImputer(strategy="most_frequent")
|
|
44
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
45
|
+
log.append(f"Imputed '{col}' with mode.")
|
|
46
|
+
elif rec.method in ("unknown_category", "recode_not_applicable"):
|
|
47
|
+
fill_val = "None/Not applicable" if rec.method == "recode_not_applicable" else "Unknown"
|
|
48
|
+
if isinstance(out[col].dtype, pd.CategoricalDtype):
|
|
49
|
+
if fill_val not in out[col].cat.categories:
|
|
50
|
+
out[col] = out[col].cat.add_categories([fill_val])
|
|
51
|
+
out[col] = out[col].fillna(fill_val)
|
|
52
|
+
log.append(f"Filled '{col}' missing values with '{fill_val}'.")
|
|
53
|
+
elif rec.method in ("interpolate", "interpolate_short_flag_long"):
|
|
54
|
+
limit = config.short_gap_limit if rec.method == "interpolate_short_flag_long" else None
|
|
55
|
+
if rec.method == "interpolate_short_flag_long":
|
|
56
|
+
out[f"{col}_was_missing"] = out[col].isna().astype(int)
|
|
57
|
+
out[col] = out[col].interpolate(method="linear", limit=limit, limit_direction="both")
|
|
58
|
+
if out[col].isna().any():
|
|
59
|
+
imp = SimpleImputer(strategy="median")
|
|
60
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
61
|
+
log.append(f"Interpolated '{col}' ({rec.method}).")
|
|
62
|
+
elif rec.method == "knn":
|
|
63
|
+
use_cols = [c for c in ([col] + rec.drivers) if c in numeric_cols]
|
|
64
|
+
if len(use_cols) < 2:
|
|
65
|
+
use_cols = numeric_cols
|
|
66
|
+
if len(use_cols) >= 2:
|
|
67
|
+
imp = KNNImputer(n_neighbors=5)
|
|
68
|
+
imputed = imp.fit_transform(out[use_cols])
|
|
69
|
+
out[col] = imputed[:, use_cols.index(col)]
|
|
70
|
+
log.append(f"Imputed '{col}' with KNNImputer using {use_cols}.")
|
|
71
|
+
else:
|
|
72
|
+
imp = SimpleImputer(strategy="median")
|
|
73
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
74
|
+
log.append(f"Imputed '{col}' with median fallback.")
|
|
75
|
+
elif rec.method == "iterative":
|
|
76
|
+
use_cols = numeric_cols if len(numeric_cols) >= 2 else [col]
|
|
77
|
+
if len(use_cols) >= 2:
|
|
78
|
+
imp = IterativeImputer(random_state=42, max_iter=10)
|
|
79
|
+
imputed = imp.fit_transform(out[use_cols])
|
|
80
|
+
out[col] = imputed[:, use_cols.index(col)]
|
|
81
|
+
log.append(f"Imputed '{col}' with IterativeImputer.")
|
|
82
|
+
else:
|
|
83
|
+
imp = SimpleImputer(strategy="median")
|
|
84
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
85
|
+
log.append(f"Imputed '{col}' with median fallback.")
|
|
86
|
+
elif rec.method == "flag_only":
|
|
87
|
+
out[f"{col}_was_missing"] = out[col].isna().astype(int)
|
|
88
|
+
log.append(f"Added '{col}_was_missing' flag without imputing '{col}'.")
|
|
89
|
+
elif rec.method == "flag_and_impute":
|
|
90
|
+
out[f"{col}_was_missing"] = out[col].isna().astype(int)
|
|
91
|
+
if pd.api.types.is_numeric_dtype(out[col]):
|
|
92
|
+
imp = SimpleImputer(strategy="median")
|
|
93
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
94
|
+
else:
|
|
95
|
+
imp = SimpleImputer(strategy="most_frequent")
|
|
96
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
97
|
+
log.append(f"Added '{col}_was_missing' flag and imputed '{col}'.")
|
|
98
|
+
|
|
99
|
+
return out, log
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Typer CLI for missinglens."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from missinglens.report import analyze
|
|
12
|
+
|
|
13
|
+
app = typer.Typer(help="Analyze missing data per column and generate recommendations.")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def main(
|
|
18
|
+
csv_path: Path = typer.Argument(..., exists=True, help="Path to input CSV file."),
|
|
19
|
+
time_col: Optional[str] = typer.Option(None, "--time-col", help="Optional timestamp column."),
|
|
20
|
+
out: Optional[Path] = typer.Option(None, "--out", help="Optional output HTML report path."),
|
|
21
|
+
) -> None:
|
|
22
|
+
"""Analyze a CSV file for missing data patterns and recommendations."""
|
|
23
|
+
df = pd.read_csv(csv_path)
|
|
24
|
+
report = analyze(df, time_col=time_col)
|
|
25
|
+
typer.echo(report.summary().to_string(index=False))
|
|
26
|
+
if out is not None:
|
|
27
|
+
report.to_html(out)
|
|
28
|
+
typer.echo(f"\nSaved HTML report to {out}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
app()
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Configuration and calibrated thresholds for missinglens."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class ThresholdConfig:
|
|
8
|
+
"""Thresholds used by pattern detectors and recommender."""
|
|
9
|
+
|
|
10
|
+
alpha: float = 0.01
|
|
11
|
+
min_samples: int = 20
|
|
12
|
+
min_missing_for_test: int = 15
|
|
13
|
+
trend_rho_threshold: float = 0.25
|
|
14
|
+
mar_auc_threshold: float = 0.65
|
|
15
|
+
comissing_corr_threshold: float = 0.40
|
|
16
|
+
block_min_length: int = 5
|
|
17
|
+
drop_threshold_pct: float = 60.0
|
|
18
|
+
short_gap_limit: int = 5
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
DEFAULT_CONFIG = ThresholdConfig()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# End-to-end min(TREND, SEASONAL) recall lookup: (n_rows, missing_count, power)
|
|
25
|
+
POWER_TABLE: tuple[tuple[int, int, float], ...] = (
|
|
26
|
+
(10000, 1000, 1.00),
|
|
27
|
+
(10000, 200, 0.60),
|
|
28
|
+
(1000, 100, 0.88),
|
|
29
|
+
(1000, 50, 0.36),
|
|
30
|
+
(1000, 20, 0.06),
|
|
31
|
+
(200, 40, 0.88),
|
|
32
|
+
(200, 20, 0.32),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def estimate_detection_power(n_rows: int, missing_count: int) -> float:
|
|
37
|
+
"""Estimate end-to-end detection power for TREND/SEASONAL from (n_rows, missing_count)."""
|
|
38
|
+
if n_rows < 100 or missing_count < 15:
|
|
39
|
+
return 0.10
|
|
40
|
+
if n_rows >= 10000:
|
|
41
|
+
return 1.00 if missing_count >= 500 else 0.60
|
|
42
|
+
if n_rows >= 1000:
|
|
43
|
+
return 0.88 if missing_count >= 90 else 0.36
|
|
44
|
+
return 0.88 if missing_count >= 40 else 0.32
|