klib 1.1.1__tar.gz → 1.2.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.
- {klib-1.1.1 → klib-1.2.0}/PKG-INFO +7 -5
- {klib-1.1.1 → klib-1.2.0}/README.md +1 -0
- {klib-1.1.1 → klib-1.2.0}/pyproject.toml +33 -80
- {klib-1.1.1 → klib-1.2.0}/src/klib/_version.py +1 -1
- {klib-1.1.1 → klib-1.2.0}/src/klib/clean.py +16 -15
- {klib-1.1.1 → klib-1.2.0}/src/klib/describe.py +58 -37
- {klib-1.1.1 → klib-1.2.0}/src/klib/scripts/performance.py +1 -0
- {klib-1.1.1 → klib-1.2.0}/src/klib/utils.py +10 -8
- {klib-1.1.1 → klib-1.2.0}/tests/test_clean.py +13 -20
- {klib-1.1.1 → klib-1.2.0}/tests/test_describe.py +1 -2
- {klib-1.1.1 → klib-1.2.0}/tests/test_util.py +96 -80
- {klib-1.1.1 → klib-1.2.0}/LICENSE +0 -0
- {klib-1.1.1 → klib-1.2.0}/src/klib/__init__.py +0 -0
- {klib-1.1.1 → klib-1.2.0}/src/klib/scripts/__init__.py +0 -0
- {klib-1.1.1 → klib-1.2.0}/tests/__init__.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: klib
|
|
3
|
-
Version: 1.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Common data preprocessing and visualisation functions.
|
|
5
5
|
License: MIT
|
|
6
6
|
Author: Andreas Kanz
|
|
7
7
|
Author-email: andreas@akanz.de
|
|
@@ -12,12 +12,13 @@ Classifier: Programming Language :: Python :: 3.8
|
|
|
12
12
|
Classifier: Programming Language :: Python :: 3.9
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.10
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
16
|
Requires-Dist: Jinja2 (>=3.0.3,<4.0.0)
|
|
16
|
-
Requires-Dist: matplotlib (>=3.
|
|
17
|
-
Requires-Dist: numpy (>=1.
|
|
17
|
+
Requires-Dist: matplotlib (>=3.4.3,<4.0.0)
|
|
18
|
+
Requires-Dist: numpy (>=1.21.6,<2.0.0)
|
|
18
19
|
Requires-Dist: pandas (>=1.2,<3.0)
|
|
19
20
|
Requires-Dist: plotly (>=5.2.2,<6.0.0)
|
|
20
|
-
Requires-Dist: scipy (>=1.
|
|
21
|
+
Requires-Dist: scipy (>=1.7.3,<2.0.0)
|
|
21
22
|
Requires-Dist: screeninfo (>=0.8.1,<0.9.0)
|
|
22
23
|
Requires-Dist: seaborn (>=0.11.2)
|
|
23
24
|
Description-Content-Type: text/markdown
|
|
@@ -65,6 +66,7 @@ df = pd.DataFrame(data)
|
|
|
65
66
|
- klib.cat_plot(df) # returns a visualization of the number and frequency of categorical features
|
|
66
67
|
- klib.corr_mat(df) # returns a color-encoded correlation matrix
|
|
67
68
|
- klib.corr_plot(df) # returns a color-encoded heatmap, ideal for correlations
|
|
69
|
+
- klib.corr_interactive_plot(df, split="neg").show() # returns an interactive correlation plot using plotly
|
|
68
70
|
- klib.dist_plot(df) # returns a distribution plot for every numeric feature
|
|
69
71
|
- klib.missingval_plot(df) # returns a figure containing information about missing values
|
|
70
72
|
|
|
@@ -41,6 +41,7 @@ df = pd.DataFrame(data)
|
|
|
41
41
|
- klib.cat_plot(df) # returns a visualization of the number and frequency of categorical features
|
|
42
42
|
- klib.corr_mat(df) # returns a color-encoded correlation matrix
|
|
43
43
|
- klib.corr_plot(df) # returns a color-encoded heatmap, ideal for correlations
|
|
44
|
+
- klib.corr_interactive_plot(df, split="neg").show() # returns an interactive correlation plot using plotly
|
|
44
45
|
- klib.dist_plot(df) # returns a distribution plot for every numeric feature
|
|
45
46
|
- klib.missingval_plot(df) # returns a figure containing information about missing values
|
|
46
47
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "klib"
|
|
3
|
-
version = "1.
|
|
4
|
-
description = "
|
|
3
|
+
version = "1.2.0"
|
|
4
|
+
description = "Common data preprocessing and visualisation functions."
|
|
5
5
|
authors = ["Andreas Kanz <andreas@akanz.de>"]
|
|
6
6
|
license = "MIT"
|
|
7
7
|
readme = "README.md"
|
|
@@ -11,38 +11,29 @@ include = [{ path = "tests", format = "sdist" }]
|
|
|
11
11
|
|
|
12
12
|
[tool.poetry.dependencies]
|
|
13
13
|
Jinja2 = "^3.0.3"
|
|
14
|
-
matplotlib = "^3.
|
|
15
|
-
numpy = "^1.
|
|
14
|
+
matplotlib = "^3.4.3"
|
|
15
|
+
numpy = "^1.21.6"
|
|
16
16
|
pandas = ">=1.2,<3.0"
|
|
17
17
|
plotly = "^5.2.2"
|
|
18
18
|
python = ">=3.8.0,<4.0.0"
|
|
19
|
-
scipy = "^1.
|
|
19
|
+
scipy = "^1.7.3"
|
|
20
20
|
screeninfo = "^0.8.1"
|
|
21
21
|
seaborn = ">=0.11.2"
|
|
22
22
|
|
|
23
23
|
[tool.poetry.dev-dependencies]
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
pre-commit = "^3.3.3"
|
|
24
|
+
ipykernel = "^6.29.5"
|
|
25
|
+
mypy = "^1.11.0"
|
|
26
|
+
nbformat = "^5.10.4"
|
|
27
|
+
pre-commit = "^3.5.0"
|
|
29
28
|
pydocstyle = "^6.2.3"
|
|
30
|
-
pytest = "^
|
|
31
|
-
pytest-cov = "^
|
|
32
|
-
ruff = "
|
|
29
|
+
pytest = "^8.3.1"
|
|
30
|
+
pytest-cov = "^5.0.0"
|
|
31
|
+
ruff = ">=0.5.5"
|
|
33
32
|
|
|
34
33
|
[build-system]
|
|
35
34
|
requires = ["poetry-core>=1.0.0"]
|
|
36
35
|
build-backend = "poetry.core.masonry.api"
|
|
37
36
|
|
|
38
|
-
[tool.black]
|
|
39
|
-
target_version = ['py37', 'py38', 'py39', 'py310', 'py311']
|
|
40
|
-
|
|
41
|
-
[tool.isort]
|
|
42
|
-
profile = "black"
|
|
43
|
-
skip_gitignore = true
|
|
44
|
-
force_single_line = true
|
|
45
|
-
|
|
46
37
|
[tool.pydocstyle]
|
|
47
38
|
match_dir = "[^(?!tests|\\.)].*" # not tests and not a folder that starts with a dot
|
|
48
39
|
match = "^(?!(__init__|setup)).*py$" # py files which do not start with __init__ or setup
|
|
@@ -74,7 +65,7 @@ fail_under = 0
|
|
|
74
65
|
|
|
75
66
|
[tool.ruff]
|
|
76
67
|
fix = true
|
|
77
|
-
unfixable = [
|
|
68
|
+
lint.unfixable = [
|
|
78
69
|
"C408",
|
|
79
70
|
"D200",
|
|
80
71
|
"D400",
|
|
@@ -91,67 +82,29 @@ unfixable = [
|
|
|
91
82
|
"SIM108",
|
|
92
83
|
]
|
|
93
84
|
|
|
94
|
-
select = [
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
"
|
|
98
|
-
"
|
|
99
|
-
"
|
|
100
|
-
"
|
|
101
|
-
"
|
|
102
|
-
"
|
|
103
|
-
"
|
|
104
|
-
"
|
|
105
|
-
"DJ",
|
|
106
|
-
"DTZ",
|
|
107
|
-
"E",
|
|
108
|
-
"EM",
|
|
109
|
-
"ERA",
|
|
110
|
-
"EXE",
|
|
111
|
-
"F",
|
|
112
|
-
"FBT",
|
|
113
|
-
"G",
|
|
114
|
-
"I",
|
|
115
|
-
"ICN",
|
|
116
|
-
"INP",
|
|
117
|
-
"ISC",
|
|
118
|
-
"N",
|
|
119
|
-
"NPY",
|
|
120
|
-
"PD",
|
|
121
|
-
"PGH",
|
|
122
|
-
"PIE",
|
|
123
|
-
"PL",
|
|
124
|
-
"PT",
|
|
125
|
-
"PTH",
|
|
126
|
-
"PYI",
|
|
127
|
-
"Q",
|
|
128
|
-
"RET",
|
|
129
|
-
"RSE",
|
|
130
|
-
"RUF",
|
|
131
|
-
"S",
|
|
132
|
-
"SIM",
|
|
133
|
-
"SLF",
|
|
134
|
-
"T",
|
|
135
|
-
"T10",
|
|
136
|
-
"T20",
|
|
137
|
-
"TCH",
|
|
138
|
-
"TID",
|
|
139
|
-
"TRY",
|
|
140
|
-
"UP",
|
|
141
|
-
"W",
|
|
142
|
-
"YTT",
|
|
85
|
+
lint.select = ["ALL"]
|
|
86
|
+
|
|
87
|
+
lint.ignore = [
|
|
88
|
+
"T201",
|
|
89
|
+
"FBT001",
|
|
90
|
+
"FBT002",
|
|
91
|
+
"PLR0913",
|
|
92
|
+
"D213",
|
|
93
|
+
"D203",
|
|
94
|
+
"UP038",
|
|
95
|
+
"PD901",
|
|
143
96
|
]
|
|
144
97
|
|
|
145
|
-
|
|
98
|
+
line-length = 100
|
|
99
|
+
target-version = "py310"
|
|
146
100
|
|
|
147
|
-
|
|
148
|
-
|
|
101
|
+
[tool.ruff.lint.mccabe]
|
|
102
|
+
max-complexity = 8
|
|
149
103
|
|
|
150
|
-
[tool.ruff.
|
|
151
|
-
|
|
104
|
+
[tool.ruff.lint.per-file-ignores]
|
|
105
|
+
"test**" = ["ANN", "D", "S101", "PLR", "PT009", "PT011", "N", "E501", "N801"]
|
|
106
|
+
"**/scripts/**" = ["ANN", "D", "S101", "PLR", "PT009", "PT011", "N", "E501"]
|
|
152
107
|
|
|
153
|
-
[tool.ruff.
|
|
154
|
-
"test**" = ["ANN", "D", "S101", "PLR", "PT009", "N", "E501"]
|
|
155
|
-
"**/scripts/**" = ["ANN", "D", "S101", "PLR", "PT009", "N", "E501"]
|
|
156
|
-
[tool.ruff.isort]
|
|
108
|
+
[tool.ruff.lint.isort]
|
|
157
109
|
force-single-line = true
|
|
110
|
+
order-by-type = false
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
:author: Andreas Kanz
|
|
4
4
|
"""
|
|
5
|
+
|
|
5
6
|
from __future__ import annotations
|
|
6
7
|
|
|
7
8
|
import itertools
|
|
@@ -28,7 +29,7 @@ __all__ = [
|
|
|
28
29
|
|
|
29
30
|
|
|
30
31
|
def _optimize_ints(data: pd.Series | pd.DataFrame) -> pd.DataFrame:
|
|
31
|
-
df = pd.DataFrame(data).copy()
|
|
32
|
+
df = pd.DataFrame(data).copy()
|
|
32
33
|
ints = df.select_dtypes(include=["int64"]).columns.tolist()
|
|
33
34
|
df[ints] = df[ints].apply(pd.to_numeric, downcast="integer")
|
|
34
35
|
return df
|
|
@@ -41,7 +42,7 @@ def _optimize_floats(data: pd.Series | pd.DataFrame) -> pd.DataFrame:
|
|
|
41
42
|
return data
|
|
42
43
|
|
|
43
44
|
|
|
44
|
-
def clean_column_names(data: pd.DataFrame, hints: bool = True) -> pd.DataFrame:
|
|
45
|
+
def clean_column_names(data: pd.DataFrame, *, hints: bool = True) -> pd.DataFrame:
|
|
45
46
|
"""Clean the column names of the provided Pandas Dataframe.
|
|
46
47
|
|
|
47
48
|
Optionally provides hints on duplicate and long column names.
|
|
@@ -58,6 +59,7 @@ def clean_column_names(data: pd.DataFrame, hints: bool = True) -> pd.DataFrame:
|
|
|
58
59
|
-------
|
|
59
60
|
pd.DataFrame
|
|
60
61
|
Pandas DataFrame with cleaned column names
|
|
62
|
+
|
|
61
63
|
"""
|
|
62
64
|
_validate_input_bool(hints, "hints")
|
|
63
65
|
|
|
@@ -115,7 +117,9 @@ def clean_column_names(data: pd.DataFrame, hints: bool = True) -> pd.DataFrame:
|
|
|
115
117
|
)
|
|
116
118
|
|
|
117
119
|
if long_col_names := [
|
|
118
|
-
x
|
|
120
|
+
x
|
|
121
|
+
for x in data.columns
|
|
122
|
+
if len(x) > 25 # noqa: PLR2004
|
|
119
123
|
]:
|
|
120
124
|
print_statement += (
|
|
121
125
|
"Long column names detected (>25 characters). Consider renaming "
|
|
@@ -155,6 +159,7 @@ def convert_datatypes(
|
|
|
155
159
|
-------
|
|
156
160
|
pd.DataFrame
|
|
157
161
|
Pandas DataFrame with converted Datatypes
|
|
162
|
+
|
|
158
163
|
"""
|
|
159
164
|
# Validate Inputs
|
|
160
165
|
_validate_input_bool(category, "Category")
|
|
@@ -214,6 +219,7 @@ def drop_missing(
|
|
|
214
219
|
Notes
|
|
215
220
|
-----
|
|
216
221
|
Columns are dropped first
|
|
222
|
+
|
|
217
223
|
"""
|
|
218
224
|
# Validate Inputs
|
|
219
225
|
_validate_input_range(drop_threshold_cols, "drop_threshold_cols", 0, 1)
|
|
@@ -314,6 +320,7 @@ def data_cleaning(
|
|
|
314
320
|
-----
|
|
315
321
|
The category dtype is not grouped in the summary, unless it contains exactly the \
|
|
316
322
|
same categories.
|
|
323
|
+
|
|
317
324
|
"""
|
|
318
325
|
if col_exclude is None:
|
|
319
326
|
col_exclude = []
|
|
@@ -422,6 +429,7 @@ def mv_col_handling(
|
|
|
422
429
|
optional:
|
|
423
430
|
cols_mv: Columns with missing values included in the analysis
|
|
424
431
|
drop_cols: List of dropped columns
|
|
432
|
+
|
|
425
433
|
"""
|
|
426
434
|
# Validate Inputs
|
|
427
435
|
_validate_input_range(mv_threshold, "mv_threshold", 0, 1)
|
|
@@ -432,9 +440,7 @@ def mv_col_handling(
|
|
|
432
440
|
data_local = data.copy()
|
|
433
441
|
mv_ratios = _missing_vals(data_local)["mv_cols_ratio"]
|
|
434
442
|
cols_mv = mv_ratios[mv_ratios > mv_threshold].index.tolist()
|
|
435
|
-
data_local[cols_mv] = (
|
|
436
|
-
data_local[cols_mv].applymap(lambda x: x if pd.isna(x) else 1).fillna(0)
|
|
437
|
-
)
|
|
443
|
+
data_local[cols_mv] = data_local[cols_mv].applymap(lambda x: x if pd.isna(x) else 1).fillna(0)
|
|
438
444
|
|
|
439
445
|
high_corr_features = []
|
|
440
446
|
data_temp = data_local.copy()
|
|
@@ -448,9 +454,7 @@ def mv_col_handling(
|
|
|
448
454
|
if target is None:
|
|
449
455
|
data = data.drop(columns=high_corr_features)
|
|
450
456
|
else:
|
|
451
|
-
corrs = corr_mat(data_local, target=target, colored=False).loc[
|
|
452
|
-
high_corr_features
|
|
453
|
-
]
|
|
457
|
+
corrs = corr_mat(data_local, target=target, colored=False).loc[high_corr_features]
|
|
454
458
|
drop_cols = corrs.loc[abs(corrs.iloc[:, 0]) < corr_thresh_target].index.tolist()
|
|
455
459
|
data = data.drop(columns=drop_cols)
|
|
456
460
|
|
|
@@ -507,6 +511,7 @@ def pool_duplicate_subsets(
|
|
|
507
511
|
|
|
508
512
|
optional:
|
|
509
513
|
subset_cols: List of columns used as subset
|
|
514
|
+
|
|
510
515
|
"""
|
|
511
516
|
# Input validation
|
|
512
517
|
_validate_input_range(col_dupl_thresh, "col_dupl_thresh", 0, 1)
|
|
@@ -522,9 +527,7 @@ def pool_duplicate_subsets(
|
|
|
522
527
|
for i in range(data.shape[1] + 1 - min_col_pool):
|
|
523
528
|
# Consider only columns with lots of duplicates
|
|
524
529
|
check = [
|
|
525
|
-
col
|
|
526
|
-
for col in data.columns
|
|
527
|
-
if data.duplicated(subset=col).mean() > col_dupl_thresh
|
|
530
|
+
col for col in data.columns if data.duplicated(subset=col).mean() > col_dupl_thresh
|
|
528
531
|
]
|
|
529
532
|
|
|
530
533
|
# Identify all possible combinations for the current interation
|
|
@@ -550,9 +553,7 @@ def pool_duplicate_subsets(
|
|
|
550
553
|
subset_cols = best_subset.columns.tolist()
|
|
551
554
|
|
|
552
555
|
unique_subset = (
|
|
553
|
-
best_subset.drop_duplicates()
|
|
554
|
-
.reset_index()
|
|
555
|
-
.rename(columns={"index": "pooled_vars"})
|
|
556
|
+
best_subset.drop_duplicates().reset_index().rename(columns={"index": "pooled_vars"})
|
|
556
557
|
)
|
|
557
558
|
data = data.merge(unique_subset, how="left", on=subset_cols).drop(
|
|
558
559
|
columns=subset_cols,
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
:author: Andreas Kanz
|
|
4
4
|
|
|
5
5
|
"""
|
|
6
|
+
|
|
6
7
|
from __future__ import annotations
|
|
7
8
|
|
|
8
9
|
from typing import Any
|
|
@@ -19,6 +20,7 @@ from matplotlib.colors import LinearSegmentedColormap
|
|
|
19
20
|
from matplotlib.colors import to_rgb
|
|
20
21
|
from matplotlib.gridspec import GridSpec # noqa: TCH002
|
|
21
22
|
from screeninfo import get_monitors
|
|
23
|
+
from screeninfo import ScreenInfoError
|
|
22
24
|
|
|
23
25
|
from klib.utils import _corr_selector
|
|
24
26
|
from klib.utils import _missing_vals
|
|
@@ -71,6 +73,7 @@ def cat_plot( # noqa: C901, PLR0915
|
|
|
71
73
|
-------
|
|
72
74
|
Gridspec
|
|
73
75
|
gs: Figure with array of Axes objects
|
|
76
|
+
|
|
74
77
|
"""
|
|
75
78
|
# Validate Inputs
|
|
76
79
|
_validate_input_int(top, "top")
|
|
@@ -146,8 +149,8 @@ def cat_plot( # noqa: C901, PLR0915
|
|
|
146
149
|
# Summary stats
|
|
147
150
|
ax_bottom = fig.add_subplot(gs[1:2, count : count + 1])
|
|
148
151
|
plt.subplots_adjust(hspace=0.075)
|
|
149
|
-
ax_bottom.get_yaxis().set_visible(False)
|
|
150
|
-
ax_bottom.get_xaxis().set_visible(False)
|
|
152
|
+
ax_bottom.get_yaxis().set_visible(False)
|
|
153
|
+
ax_bottom.get_xaxis().set_visible(False)
|
|
151
154
|
ax_bottom.set(frame_on=False)
|
|
152
155
|
ax_bottom.text(
|
|
153
156
|
0,
|
|
@@ -197,6 +200,7 @@ def corr_mat(
|
|
|
197
200
|
threshold: float = 0,
|
|
198
201
|
target: pd.DataFrame | pd.Series | np.ndarray | str | None = None,
|
|
199
202
|
method: Literal["pearson", "spearman", "kendall"] = "pearson",
|
|
203
|
+
*,
|
|
200
204
|
colored: bool = True,
|
|
201
205
|
) -> pd.DataFrame | pd.Series:
|
|
202
206
|
"""Return a color-encoded correlation matrix.
|
|
@@ -232,6 +236,7 @@ def corr_mat(
|
|
|
232
236
|
pd.DataFrame | pd.Styler
|
|
233
237
|
If colored = True - corr: Pandas Styler object
|
|
234
238
|
If colored = False - corr: Pandas DataFrame
|
|
239
|
+
|
|
235
240
|
"""
|
|
236
241
|
# Validate Inputs
|
|
237
242
|
_validate_input_range(threshold, "threshold", -1, 1)
|
|
@@ -279,6 +284,7 @@ def corr_plot(
|
|
|
279
284
|
method: Literal["pearson", "spearman", "kendall"] = "pearson",
|
|
280
285
|
cmap: str = "BrBG",
|
|
281
286
|
figsize: tuple[float, float] = (12, 10),
|
|
287
|
+
*,
|
|
282
288
|
annot: bool = True,
|
|
283
289
|
dev: bool = False,
|
|
284
290
|
**kwargs, # noqa: ANN003
|
|
@@ -357,6 +363,7 @@ def corr_plot(
|
|
|
357
363
|
-------
|
|
358
364
|
ax: matplotlib Axes
|
|
359
365
|
Returns the Axes object with the plot for further tweaking.
|
|
366
|
+
|
|
360
367
|
"""
|
|
361
368
|
# Validate Inputs
|
|
362
369
|
_validate_input_range(threshold, "threshold", -1, 1)
|
|
@@ -427,7 +434,7 @@ def corr_plot(
|
|
|
427
434
|
return ax
|
|
428
435
|
|
|
429
436
|
|
|
430
|
-
def corr_interactive_plot(
|
|
437
|
+
def corr_interactive_plot( # noqa: C901
|
|
431
438
|
data: pd.DataFrame,
|
|
432
439
|
split: Literal["pos", "neg", "high", "low"] | None = None,
|
|
433
440
|
threshold: float = 0.0,
|
|
@@ -435,6 +442,7 @@ def corr_interactive_plot(
|
|
|
435
442
|
method: Literal["pearson", "spearman", "kendall"] = "pearson",
|
|
436
443
|
cmap: str = "BrBG",
|
|
437
444
|
figsize: tuple[float, float] = (12, 10),
|
|
445
|
+
*,
|
|
438
446
|
annot: bool = True,
|
|
439
447
|
**kwargs, # noqa: ANN003
|
|
440
448
|
) -> go.Figure:
|
|
@@ -557,6 +565,7 @@ def corr_interactive_plot(
|
|
|
557
565
|
heatmap : plotly.graph_objs._figure.Figure
|
|
558
566
|
A Plotly Figure object representing the heatmap visualization of
|
|
559
567
|
feature correlations.
|
|
568
|
+
|
|
560
569
|
"""
|
|
561
570
|
# Validate Inputs
|
|
562
571
|
_validate_input_range(threshold, "threshold", -1, 1)
|
|
@@ -590,6 +599,15 @@ def corr_interactive_plot(
|
|
|
590
599
|
|
|
591
600
|
vtext = corr.round(2).fillna("") if annot else None
|
|
592
601
|
|
|
602
|
+
corr_columns = corr.columns
|
|
603
|
+
corr_index = corr.index
|
|
604
|
+
|
|
605
|
+
if isinstance(corr_columns, pd.MultiIndex):
|
|
606
|
+
corr_columns = ["-".join(col) for col in corr.columns]
|
|
607
|
+
|
|
608
|
+
if isinstance(corr_index, pd.MultiIndex):
|
|
609
|
+
corr_index = ["-".join(idx) for idx in corr.index]
|
|
610
|
+
|
|
593
611
|
# Specify kwargs for the heatmap
|
|
594
612
|
kwargs = {
|
|
595
613
|
"colorscale": cmap,
|
|
@@ -598,8 +616,8 @@ def corr_interactive_plot(
|
|
|
598
616
|
"text": vtext,
|
|
599
617
|
"texttemplate": "%{text}",
|
|
600
618
|
"textfont": {"size": 12},
|
|
601
|
-
"x":
|
|
602
|
-
"y":
|
|
619
|
+
"x": corr_columns,
|
|
620
|
+
"y": corr_index,
|
|
603
621
|
"z": corr,
|
|
604
622
|
**kwargs,
|
|
605
623
|
}
|
|
@@ -615,19 +633,22 @@ def corr_interactive_plot(
|
|
|
615
633
|
)
|
|
616
634
|
|
|
617
635
|
dpi = None
|
|
618
|
-
|
|
619
|
-
|
|
636
|
+
try:
|
|
637
|
+
for monitor in get_monitors():
|
|
638
|
+
if monitor.is_primary:
|
|
639
|
+
if monitor.width_mm is None or monitor.height_mm is None:
|
|
640
|
+
continue
|
|
641
|
+
dpi = monitor.width / (monitor.width_mm / 25.4)
|
|
642
|
+
break
|
|
643
|
+
|
|
644
|
+
if dpi is None:
|
|
645
|
+
monitor = get_monitors()[0]
|
|
620
646
|
if monitor.width_mm is None or monitor.height_mm is None:
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
monitor = get_monitors()[0]
|
|
627
|
-
if monitor.width_mm is None or monitor.height_mm is None:
|
|
628
|
-
dpi = 96 # more or less arbitrary default value
|
|
629
|
-
else:
|
|
630
|
-
dpi = monitor.width / (monitor.width_mm / 25.4)
|
|
647
|
+
dpi = 96 # more or less arbitrary default value
|
|
648
|
+
else:
|
|
649
|
+
dpi = monitor.width / (monitor.width_mm / 25.4)
|
|
650
|
+
except ScreenInfoError:
|
|
651
|
+
dpi = 96
|
|
631
652
|
|
|
632
653
|
heatmap.update_layout(
|
|
633
654
|
title=f"Feature-correlation ({method})",
|
|
@@ -686,6 +707,7 @@ def dist_plot(
|
|
|
686
707
|
-------
|
|
687
708
|
ax: matplotlib Axes
|
|
688
709
|
Returns the Axes object with the plot for further tweaking.
|
|
710
|
+
|
|
689
711
|
"""
|
|
690
712
|
# Validate Inputs
|
|
691
713
|
_validate_input_range(fill_range[0], "fill_range_lower", 0, 1)
|
|
@@ -695,18 +717,14 @@ def dist_plot(
|
|
|
695
717
|
|
|
696
718
|
# Handle dictionary defaults
|
|
697
719
|
kde_kws = (
|
|
698
|
-
{"alpha": 0.75, "linewidth": 1.5, "bw_adjust": 0.8}
|
|
699
|
-
if kde_kws is None
|
|
700
|
-
else kde_kws.copy()
|
|
720
|
+
{"alpha": 0.75, "linewidth": 1.5, "bw_adjust": 0.8} if kde_kws is None else kde_kws.copy()
|
|
701
721
|
)
|
|
702
722
|
rug_kws = (
|
|
703
723
|
{"color": "#ff3333", "alpha": 0.15, "lw": 3, "height": 0.075}
|
|
704
724
|
if rug_kws is None
|
|
705
725
|
else rug_kws.copy()
|
|
706
726
|
)
|
|
707
|
-
fill_kws = (
|
|
708
|
-
{"color": "#80d4ff", "alpha": 0.2} if fill_kws is None else fill_kws.copy()
|
|
709
|
-
)
|
|
727
|
+
fill_kws = {"color": "#80d4ff", "alpha": 0.2} if fill_kws is None else fill_kws.copy()
|
|
710
728
|
font_kws = (
|
|
711
729
|
{"color": "#111111", "weight": "normal", "size": 11}
|
|
712
730
|
if font_kws is None
|
|
@@ -714,7 +732,7 @@ def dist_plot(
|
|
|
714
732
|
)
|
|
715
733
|
|
|
716
734
|
data = pd.DataFrame(data.copy()).dropna(axis=1, how="all")
|
|
717
|
-
df = data.copy()
|
|
735
|
+
df = data.copy()
|
|
718
736
|
data = data.loc[:, data.nunique() > 2] # noqa: PLR2004
|
|
719
737
|
if data.shape[0] > 10000: # noqa: PLR2004
|
|
720
738
|
data = data.sample(n=10000, random_state=408)
|
|
@@ -736,6 +754,9 @@ def dist_plot(
|
|
|
736
754
|
"the first 20 numerical features. Override this by setting showall=True.",
|
|
737
755
|
)
|
|
738
756
|
cols = cols[:20]
|
|
757
|
+
if not cols:
|
|
758
|
+
print("No columns with numeric data were detected.")
|
|
759
|
+
return None
|
|
739
760
|
|
|
740
761
|
for col in cols:
|
|
741
762
|
col_data = data[col].dropna(axis=0)
|
|
@@ -790,7 +811,7 @@ def dist_plot(
|
|
|
790
811
|
ymax=[np.interp(mean - std, x, y), np.interp(mean + std, x, y)],
|
|
791
812
|
ls=":",
|
|
792
813
|
color=".5",
|
|
793
|
-
label="\
|
|
814
|
+
label="\u03bc \u00b1 \u03c3",
|
|
794
815
|
)
|
|
795
816
|
|
|
796
817
|
g.axes[0, 0].set_ylim(0)
|
|
@@ -837,8 +858,7 @@ def dist_plot(
|
|
|
837
858
|
)
|
|
838
859
|
g.axes[0, 0].legend(loc="upper right")
|
|
839
860
|
|
|
840
|
-
|
|
841
|
-
return None
|
|
861
|
+
return g.axes[0, 0]
|
|
842
862
|
|
|
843
863
|
|
|
844
864
|
def missingval_plot( # noqa: PLR0915
|
|
@@ -871,6 +891,7 @@ def missingval_plot( # noqa: PLR0915
|
|
|
871
891
|
-------
|
|
872
892
|
GridSpec
|
|
873
893
|
gs: Figure with array of Axes objects
|
|
894
|
+
|
|
874
895
|
"""
|
|
875
896
|
# Validate Inputs
|
|
876
897
|
_validate_input_bool(sort, "sort")
|
|
@@ -908,7 +929,7 @@ def missingval_plot( # noqa: PLR0915
|
|
|
908
929
|
# ax1 - Barplot
|
|
909
930
|
colors = plt.get_cmap(cmap)(mv_cols / np.max(mv_cols)) # color bars by height
|
|
910
931
|
ax1.bar(range(len(mv_cols)), np.round((mv_cols_ratio) * 100, 2), color=colors)
|
|
911
|
-
ax1.get_xaxis().set_visible(False)
|
|
932
|
+
ax1.get_xaxis().set_visible(False)
|
|
912
933
|
ax1.set(frame_on=False, xlim=(-0.5, len(mv_cols) - 0.5))
|
|
913
934
|
ax1.set_ylim(0, np.max(mv_cols_ratio) * 100)
|
|
914
935
|
ax1.grid(linestyle=":", linewidth=1)
|
|
@@ -929,9 +950,9 @@ def missingval_plot( # noqa: PLR0915
|
|
|
929
950
|
fontsize="11",
|
|
930
951
|
)
|
|
931
952
|
|
|
932
|
-
ax1.set_frame_on(True)
|
|
933
|
-
for
|
|
934
|
-
spine.set_visible(True)
|
|
953
|
+
ax1.set_frame_on(True)
|
|
954
|
+
for spine in ax1.spines.values():
|
|
955
|
+
spine.set_visible(True)
|
|
935
956
|
spine.set_color(spine_color)
|
|
936
957
|
ax1.spines["top"].set_color(None)
|
|
937
958
|
|
|
@@ -946,14 +967,14 @@ def missingval_plot( # noqa: PLR0915
|
|
|
946
967
|
fontsize="12",
|
|
947
968
|
)
|
|
948
969
|
ax2.tick_params(length=1, colors="#111111")
|
|
949
|
-
for
|
|
950
|
-
spine.set_visible(True)
|
|
970
|
+
for spine in ax2.spines.values():
|
|
971
|
+
spine.set_visible(True)
|
|
951
972
|
spine.set_color(spine_color)
|
|
952
973
|
|
|
953
974
|
# ax3 - Summary
|
|
954
975
|
fontax3 = {"color": "#111111", "weight": "normal", "size": 14}
|
|
955
|
-
ax3.get_xaxis().set_visible(False)
|
|
956
|
-
ax3.get_yaxis().set_visible(False)
|
|
976
|
+
ax3.get_xaxis().set_visible(False)
|
|
977
|
+
ax3.get_yaxis().set_visible(False)
|
|
957
978
|
ax3.set(frame_on=False)
|
|
958
979
|
|
|
959
980
|
ax3.text(
|
|
@@ -993,8 +1014,8 @@ def missingval_plot( # noqa: PLR0915
|
|
|
993
1014
|
)
|
|
994
1015
|
|
|
995
1016
|
# ax4 - Scatter plot
|
|
996
|
-
ax4.get_yaxis().set_visible(False)
|
|
997
|
-
for
|
|
1017
|
+
ax4.get_yaxis().set_visible(False)
|
|
1018
|
+
for spine in ax4.spines.values():
|
|
998
1019
|
spine.set_color(spine_color)
|
|
999
1020
|
ax4.tick_params(axis="x", colors="#111111", length=1)
|
|
1000
1021
|
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
:author: Andreas Kanz
|
|
4
4
|
|
|
5
5
|
"""
|
|
6
|
+
|
|
6
7
|
from __future__ import annotations
|
|
7
8
|
|
|
8
9
|
from typing import Literal
|
|
@@ -34,6 +35,7 @@ def _corr_selector(
|
|
|
34
35
|
-------
|
|
35
36
|
pd.DataFrame
|
|
36
37
|
List or matrix of (filtered) correlations
|
|
38
|
+
|
|
37
39
|
"""
|
|
38
40
|
if split == "pos":
|
|
39
41
|
corr = corr.where((corr >= threshold) & (corr > 0))
|
|
@@ -102,6 +104,7 @@ def _diff_report(
|
|
|
102
104
|
-------
|
|
103
105
|
None
|
|
104
106
|
Print statement highlighting the datasets or changes between the two datasets.
|
|
107
|
+
|
|
105
108
|
"""
|
|
106
109
|
if show not in ["changes", "all"]:
|
|
107
110
|
return
|
|
@@ -125,17 +128,15 @@ def _diff_report(
|
|
|
125
128
|
)
|
|
126
129
|
|
|
127
130
|
print(
|
|
128
|
-
f"Shape of cleaned data: {data_cleaned.shape} - "
|
|
129
|
-
f"Remaining NAs: {data_cl_mv_tot}\n\n",
|
|
131
|
+
f"Shape of cleaned data: {data_cleaned.shape} - Remaining NAs: {data_cl_mv_tot}\n\n",
|
|
130
132
|
)
|
|
131
133
|
print(f"Dropped rows: {data.shape[0]-data_cleaned.shape[0]}")
|
|
132
134
|
print(
|
|
133
|
-
f" of which {len(dupl_rows)} duplicates. (Rows (first 150 shown): {dupl_rows[:150]})\n",
|
|
135
|
+
f" of which {len(dupl_rows)} duplicates. (Rows (first 150 shown): {dupl_rows[:150]})\n",
|
|
134
136
|
)
|
|
135
137
|
print(f"Dropped columns: {data.shape[1]-data_cleaned.shape[1]}")
|
|
136
138
|
print(
|
|
137
|
-
f" of which {len(single_val_cols)} single valued."
|
|
138
|
-
f" Columns: {single_val_cols}",
|
|
139
|
+
f" of which {len(single_val_cols)} single valued. Columns: {single_val_cols}",
|
|
139
140
|
)
|
|
140
141
|
print(f"Dropped missing values: {data_mv_tot-data_cl_mv_tot}")
|
|
141
142
|
mem_change = data_mem - data_cl_mem
|
|
@@ -170,6 +171,7 @@ def _drop_duplicates(data: pd.DataFrame) -> tuple[pd.DataFrame, list[str | int]]
|
|
|
170
171
|
-------
|
|
171
172
|
Tuple[pd.DataFrame, List]
|
|
172
173
|
Deduplicated Pandas DataFrame and Index Object of rows dropped
|
|
174
|
+
|
|
173
175
|
"""
|
|
174
176
|
data = pd.DataFrame(data).copy()
|
|
175
177
|
dupl_rows = data[data.duplicated()].index.tolist()
|
|
@@ -192,6 +194,7 @@ def _memory_usage(data: pd.DataFrame, deep: bool = True) -> float:
|
|
|
192
194
|
-------
|
|
193
195
|
float
|
|
194
196
|
Memory usage in megabytes
|
|
197
|
+
|
|
195
198
|
"""
|
|
196
199
|
return round(data.memory_usage(index=True, deep=deep).sum() / (1024**2), 2)
|
|
197
200
|
|
|
@@ -222,6 +225,7 @@ def _missing_vals(data: pd.DataFrame) -> MVResult:
|
|
|
222
225
|
mv_cols: float, number of missing values in each column
|
|
223
226
|
mv_rows_ratio: float, ratio of missing values for each row
|
|
224
227
|
mv_cols_ratio: float, ratio of missing values for each column
|
|
228
|
+
|
|
225
229
|
"""
|
|
226
230
|
data = pd.DataFrame(data).copy()
|
|
227
231
|
mv_total: int = data.isna().sum().sum()
|
|
@@ -265,9 +269,7 @@ def _validate_input_smaller(value1: int, value2: int, desc: str) -> None:
|
|
|
265
269
|
|
|
266
270
|
def _validate_input_sum_smaller(limit: float, desc: str, *args) -> None: # noqa: ANN002
|
|
267
271
|
if sum(args) > limit:
|
|
268
|
-
msg =
|
|
269
|
-
f"The sum of input values for '{desc}' should be less or equal to {limit}."
|
|
270
|
-
)
|
|
272
|
+
msg = f"The sum of input values for '{desc}' should be less or equal to {limit}."
|
|
271
273
|
raise ValueError(msg)
|
|
272
274
|
|
|
273
275
|
|
|
@@ -38,7 +38,7 @@ class Test_clean_column_names(unittest.TestCase):
|
|
|
38
38
|
)
|
|
39
39
|
cls.df_clean_column_names = pd.concat([cls.df1, cls.df2], axis=1)
|
|
40
40
|
|
|
41
|
-
def test_clean_column_names(self):
|
|
41
|
+
def test_clean_column_names(self) -> None:
|
|
42
42
|
expected_results = [
|
|
43
43
|
"asd_5_dollar_and_3_euro",
|
|
44
44
|
"3_plus_3",
|
|
@@ -54,17 +54,14 @@ class Test_clean_column_names(unittest.TestCase):
|
|
|
54
54
|
"count_larger_equal_10",
|
|
55
55
|
]
|
|
56
56
|
for i, _ in enumerate(expected_results):
|
|
57
|
-
assert (
|
|
58
|
-
clean_column_names(self.df_clean_column_names).columns[i]
|
|
59
|
-
== expected_results[i]
|
|
60
|
-
)
|
|
57
|
+
assert clean_column_names(self.df_clean_column_names).columns[i] == expected_results[i]
|
|
61
58
|
for i, _ in enumerate(expected_results):
|
|
62
59
|
assert (
|
|
63
60
|
clean_column_names(self.df_clean_column_names, hints=False).columns[i]
|
|
64
61
|
== expected_results[i]
|
|
65
62
|
)
|
|
66
63
|
|
|
67
|
-
def test_clean_column_names_prints(self):
|
|
64
|
+
def test_clean_column_names_prints(self) -> None:
|
|
68
65
|
captured_output = io.StringIO()
|
|
69
66
|
sys.stdout = captured_output
|
|
70
67
|
clean_column_names(self.df_clean_column_names, hints=True)
|
|
@@ -76,7 +73,7 @@ class Test_clean_column_names(unittest.TestCase):
|
|
|
76
73
|
|
|
77
74
|
class Test_drop_missing(unittest.TestCase):
|
|
78
75
|
@classmethod
|
|
79
|
-
def setUpClass(cls):
|
|
76
|
+
def setUpClass(cls) -> None:
|
|
80
77
|
cls.df_data_drop = pd.DataFrame(
|
|
81
78
|
[
|
|
82
79
|
[np.nan, np.nan, np.nan, np.nan, np.nan],
|
|
@@ -89,7 +86,7 @@ class Test_drop_missing(unittest.TestCase):
|
|
|
89
86
|
columns=["c1", "c2", "c3", "c4", "c5"],
|
|
90
87
|
)
|
|
91
88
|
|
|
92
|
-
def test_drop_missing(self):
|
|
89
|
+
def test_drop_missing(self) -> None:
|
|
93
90
|
assert drop_missing(self.df_data_drop).shape == (4, 4)
|
|
94
91
|
|
|
95
92
|
# Drop further columns based on threshold
|
|
@@ -127,7 +124,7 @@ class Test_drop_missing(unittest.TestCase):
|
|
|
127
124
|
|
|
128
125
|
class Test_data_cleaning(unittest.TestCase):
|
|
129
126
|
@classmethod
|
|
130
|
-
def setUpClass(cls):
|
|
127
|
+
def setUpClass(cls) -> None:
|
|
131
128
|
cls.df_data_cleaning = pd.DataFrame(
|
|
132
129
|
[
|
|
133
130
|
[np.nan, np.nan, np.nan, np.nan, np.nan, 1],
|
|
@@ -140,7 +137,7 @@ class Test_data_cleaning(unittest.TestCase):
|
|
|
140
137
|
columns=["c1", "c2", "c3", "c 4", "c5", "c6"],
|
|
141
138
|
)
|
|
142
139
|
|
|
143
|
-
def test_data_cleaning(self):
|
|
140
|
+
def test_data_cleaning(self) -> None:
|
|
144
141
|
assert data_cleaning(self.df_data_cleaning, show="all").shape == (5, 4)
|
|
145
142
|
assert data_cleaning(self.df_data_cleaning, show=None).shape == (5, 4)
|
|
146
143
|
|
|
@@ -184,7 +181,7 @@ class Test_data_cleaning(unittest.TestCase):
|
|
|
184
181
|
|
|
185
182
|
class Test_convert_dtypes(unittest.TestCase):
|
|
186
183
|
@classmethod
|
|
187
|
-
def setUpClass(cls):
|
|
184
|
+
def setUpClass(cls) -> None:
|
|
188
185
|
cls.df_data_convert = pd.DataFrame(
|
|
189
186
|
[
|
|
190
187
|
[1, 7.0, "y", "x", pd.NA, "v"],
|
|
@@ -196,7 +193,7 @@ class Test_convert_dtypes(unittest.TestCase):
|
|
|
196
193
|
],
|
|
197
194
|
)
|
|
198
195
|
|
|
199
|
-
def test_convert_dtypes(self):
|
|
196
|
+
def test_convert_dtypes(self) -> None:
|
|
200
197
|
expected_results = [
|
|
201
198
|
"int8",
|
|
202
199
|
"float32",
|
|
@@ -220,9 +217,7 @@ class Test_convert_dtypes(unittest.TestCase):
|
|
|
220
217
|
"string",
|
|
221
218
|
]
|
|
222
219
|
for i, _ in enumerate(expected_results):
|
|
223
|
-
assert (
|
|
224
|
-
convert_datatypes(self.df_data_convert).dtypes[i] == expected_results[i]
|
|
225
|
-
)
|
|
220
|
+
assert convert_datatypes(self.df_data_convert).dtypes[i] == expected_results[i]
|
|
226
221
|
|
|
227
222
|
expected_results = [
|
|
228
223
|
"int8",
|
|
@@ -275,7 +270,7 @@ class Test_convert_dtypes(unittest.TestCase):
|
|
|
275
270
|
|
|
276
271
|
class Test_pool_duplicate_subsets(unittest.TestCase):
|
|
277
272
|
@classmethod
|
|
278
|
-
def setUpClass(cls):
|
|
273
|
+
def setUpClass(cls) -> None:
|
|
279
274
|
cls.df_data_subsets = pd.DataFrame(
|
|
280
275
|
[
|
|
281
276
|
[1, 7, "d", "x", pd.NA, "v"],
|
|
@@ -288,7 +283,7 @@ class Test_pool_duplicate_subsets(unittest.TestCase):
|
|
|
288
283
|
columns=["c1", "c2", "c3", "c4", "c5", "c6"],
|
|
289
284
|
)
|
|
290
285
|
|
|
291
|
-
def test_pool_duplicate_subsets(self):
|
|
286
|
+
def test_pool_duplicate_subsets(self) -> None:
|
|
292
287
|
assert pool_duplicate_subsets(self.df_data_subsets).shape == (6, 3)
|
|
293
288
|
assert pool_duplicate_subsets(
|
|
294
289
|
self.df_data_subsets,
|
|
@@ -300,9 +295,7 @@ class Test_pool_duplicate_subsets(unittest.TestCase):
|
|
|
300
295
|
2,
|
|
301
296
|
)
|
|
302
297
|
|
|
303
|
-
assert pool_duplicate_subsets(self.df_data_subsets, return_details=True)[
|
|
304
|
-
0
|
|
305
|
-
].shape == (6, 3)
|
|
298
|
+
assert pool_duplicate_subsets(self.df_data_subsets, return_details=True)[0].shape == (6, 3)
|
|
306
299
|
assert pool_duplicate_subsets(self.df_data_subsets, return_details=True)[1] == [
|
|
307
300
|
"c1",
|
|
308
301
|
"c2",
|
|
@@ -93,8 +93,7 @@ class Test_corr_mat(unittest.TestCase):
|
|
|
93
93
|
def test_output_shape(self):
|
|
94
94
|
# Test for output dimensions
|
|
95
95
|
assert (
|
|
96
|
-
corr_mat(self.data_corr_df).data.shape[0]
|
|
97
|
-
== corr_mat(self.data_corr_df).data.shape[1]
|
|
96
|
+
corr_mat(self.data_corr_df).data.shape[0] == corr_mat(self.data_corr_df).data.shape[1]
|
|
98
97
|
)
|
|
99
98
|
assert (
|
|
100
99
|
corr_mat(self.data_corr_list).data.shape[0]
|
|
@@ -2,6 +2,7 @@ import unittest
|
|
|
2
2
|
|
|
3
3
|
import numpy as np
|
|
4
4
|
import pandas as pd
|
|
5
|
+
import pytest
|
|
5
6
|
from klib.utils import _corr_selector
|
|
6
7
|
from klib.utils import _drop_duplicates
|
|
7
8
|
from klib.utils import _missing_vals
|
|
@@ -16,7 +17,7 @@ from klib.utils import _validate_input_sum_smaller
|
|
|
16
17
|
|
|
17
18
|
class Test__corr_selector(unittest.TestCase):
|
|
18
19
|
@classmethod
|
|
19
|
-
def setUpClass(cls):
|
|
20
|
+
def setUpClass(cls) -> None:
|
|
20
21
|
cls.df_data_corr = pd.DataFrame(
|
|
21
22
|
[
|
|
22
23
|
[1, 7, 2, 2, 4, 7],
|
|
@@ -32,15 +33,9 @@ class Test__corr_selector(unittest.TestCase):
|
|
|
32
33
|
|
|
33
34
|
def test__corr_selector_matrix(self):
|
|
34
35
|
assert _corr_selector(self.df_data_corr.corr()).shape == (6, 6)
|
|
36
|
+
assert _corr_selector(self.df_data_corr.corr(), split="pos").isna().sum().sum() == 18
|
|
35
37
|
assert (
|
|
36
|
-
_corr_selector(self.df_data_corr.corr(), split="pos").isna().sum().sum()
|
|
37
|
-
== 18
|
|
38
|
-
)
|
|
39
|
-
assert (
|
|
40
|
-
_corr_selector(self.df_data_corr.corr(), split="pos", threshold=0.5)
|
|
41
|
-
.isna()
|
|
42
|
-
.sum()
|
|
43
|
-
.sum()
|
|
38
|
+
_corr_selector(self.df_data_corr.corr(), split="pos", threshold=0.5).isna().sum().sum()
|
|
44
39
|
== 26
|
|
45
40
|
)
|
|
46
41
|
assert (
|
|
@@ -58,20 +53,14 @@ class Test__corr_selector(unittest.TestCase):
|
|
|
58
53
|
== 4
|
|
59
54
|
)
|
|
60
55
|
assert (
|
|
61
|
-
_corr_selector(self.df_data_corr.corr(), split="low", threshold=0.85)
|
|
62
|
-
.isna()
|
|
63
|
-
.sum()
|
|
64
|
-
.sum()
|
|
56
|
+
_corr_selector(self.df_data_corr.corr(), split="low", threshold=0.85).isna().sum().sum()
|
|
65
57
|
== 6
|
|
66
58
|
)
|
|
67
59
|
|
|
68
60
|
def test__corr_selector_label(self):
|
|
69
61
|
assert _corr_selector(self.df_data_corr.corrwith(self.target)).shape == (6,)
|
|
70
62
|
assert (
|
|
71
|
-
_corr_selector(self.df_data_corr.corrwith(self.target), split="pos")
|
|
72
|
-
.isna()
|
|
73
|
-
.sum()
|
|
74
|
-
== 3
|
|
63
|
+
_corr_selector(self.df_data_corr.corrwith(self.target), split="pos").isna().sum() == 3
|
|
75
64
|
)
|
|
76
65
|
assert (
|
|
77
66
|
_corr_selector(
|
|
@@ -117,7 +106,7 @@ class Test__corr_selector(unittest.TestCase):
|
|
|
117
106
|
|
|
118
107
|
class Test__drop_duplicates(unittest.TestCase):
|
|
119
108
|
@classmethod
|
|
120
|
-
def setUpClass(cls
|
|
109
|
+
def setUpClass(cls) -> None:
|
|
121
110
|
cls.data_dupl_df = pd.DataFrame(
|
|
122
111
|
[
|
|
123
112
|
[pd.NA, pd.NA, pd.NA, pd.NA],
|
|
@@ -130,9 +119,9 @@ class Test__drop_duplicates(unittest.TestCase):
|
|
|
130
119
|
],
|
|
131
120
|
)
|
|
132
121
|
|
|
133
|
-
def test__drop_dupl(self):
|
|
122
|
+
def test__drop_dupl(self) -> None:
|
|
134
123
|
# Test dropping of duplicate rows
|
|
135
|
-
|
|
124
|
+
assert _drop_duplicates(self.data_dupl_df)[0].shape == (4, 4)
|
|
136
125
|
# Test if the resulting DataFrame is equal to using the pandas method
|
|
137
126
|
assert _drop_duplicates(self.data_dupl_df)[0].equals(
|
|
138
127
|
self.data_dupl_df.drop_duplicates().reset_index(drop=True),
|
|
@@ -143,7 +132,7 @@ class Test__drop_duplicates(unittest.TestCase):
|
|
|
143
132
|
|
|
144
133
|
class Test__missing_vals(unittest.TestCase):
|
|
145
134
|
@classmethod
|
|
146
|
-
def setUpClass(cls):
|
|
135
|
+
def setUpClass(cls) -> None:
|
|
147
136
|
cls.data_mv_list = [
|
|
148
137
|
[1, np.nan, 3, 4],
|
|
149
138
|
[None, 4, 5, None],
|
|
@@ -155,45 +144,39 @@ class Test__missing_vals(unittest.TestCase):
|
|
|
155
144
|
|
|
156
145
|
cls.data_mv_array = np.array(cls.data_mv_list)
|
|
157
146
|
|
|
158
|
-
def test_mv_total(self):
|
|
147
|
+
def test_mv_total(self) -> None:
|
|
159
148
|
# Test total missing values
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
149
|
+
assert _missing_vals(self.data_mv_df)["mv_total"] == 5
|
|
150
|
+
assert _missing_vals(self.data_mv_array)["mv_total"] == 5
|
|
151
|
+
assert _missing_vals(self.data_mv_list)["mv_total"] == 5
|
|
163
152
|
|
|
164
|
-
def test_mv_rows(self):
|
|
153
|
+
def test_mv_rows(self) -> None:
|
|
165
154
|
# Test missing values for each row
|
|
166
155
|
expected_results = [1, 2, 1, 1]
|
|
167
156
|
for i, result in enumerate(expected_results):
|
|
168
|
-
|
|
157
|
+
assert _missing_vals(self.data_mv_df)["mv_rows"][i] == result
|
|
169
158
|
|
|
170
|
-
def test_mv_cols(self):
|
|
159
|
+
def test_mv_cols(self) -> None:
|
|
171
160
|
# Test missing values for each column
|
|
172
161
|
expected_results = [1, 1, 1, 2]
|
|
173
162
|
for i, result in enumerate(expected_results):
|
|
174
|
-
|
|
163
|
+
assert _missing_vals(self.data_mv_df)["mv_cols"][i] == result
|
|
175
164
|
|
|
176
|
-
def test_mv_rows_ratio(self):
|
|
165
|
+
def test_mv_rows_ratio(self) -> None:
|
|
177
166
|
# Test missing values ratio for each row
|
|
178
167
|
expected_results = [0.25, 0.5, 0.25, 0.25]
|
|
179
168
|
for i, result in enumerate(expected_results):
|
|
180
|
-
self.
|
|
181
|
-
_missing_vals(self.data_mv_df)["mv_rows_ratio"][i],
|
|
182
|
-
result,
|
|
183
|
-
)
|
|
169
|
+
assert _missing_vals(self.data_mv_df)["mv_rows_ratio"][i] == result
|
|
184
170
|
|
|
185
171
|
# Test if missing value ratio is between 0 and 1
|
|
186
172
|
for i, _ in enumerate(self.data_mv_df):
|
|
187
173
|
assert 0 <= _missing_vals(self.data_mv_df)["mv_rows_ratio"][i] <= 1
|
|
188
174
|
|
|
189
|
-
def test_mv_cols_ratio(self):
|
|
175
|
+
def test_mv_cols_ratio(self) -> None:
|
|
190
176
|
# Test missing values ratio for each column
|
|
191
177
|
expected_results = [1 / 4, 0.25, 0.25, 0.5]
|
|
192
178
|
for i, result in enumerate(expected_results):
|
|
193
|
-
self.
|
|
194
|
-
_missing_vals(self.data_mv_df)["mv_cols_ratio"][i],
|
|
195
|
-
result,
|
|
196
|
-
)
|
|
179
|
+
assert _missing_vals(self.data_mv_df)["mv_cols_ratio"][i] == result
|
|
197
180
|
|
|
198
181
|
# Test if missing value ratio is between 0 and 1
|
|
199
182
|
for i, _ in enumerate(self.data_mv_df):
|
|
@@ -201,68 +184,101 @@ class Test__missing_vals(unittest.TestCase):
|
|
|
201
184
|
|
|
202
185
|
|
|
203
186
|
class Test__validate_input(unittest.TestCase):
|
|
204
|
-
def test__validate_input_bool(self):
|
|
187
|
+
def test__validate_input_bool(self) -> None:
|
|
205
188
|
# Raises an exception if the input is not boolean
|
|
206
|
-
with
|
|
207
|
-
_validate_input_bool("True",
|
|
208
|
-
with
|
|
209
|
-
_validate_input_bool(None,
|
|
210
|
-
with
|
|
211
|
-
_validate_input_bool(1,
|
|
189
|
+
with pytest.raises(TypeError):
|
|
190
|
+
_validate_input_bool("True", "No description")
|
|
191
|
+
with pytest.raises(TypeError):
|
|
192
|
+
_validate_input_bool(None, "No description")
|
|
193
|
+
with pytest.raises(TypeError):
|
|
194
|
+
_validate_input_bool(1, "No description")
|
|
212
195
|
|
|
213
|
-
def test__validate_input_int(self):
|
|
196
|
+
def test__validate_input_int(self) -> None:
|
|
214
197
|
# Raises an exception if the input is not an integer
|
|
215
|
-
with
|
|
216
|
-
_validate_input_int(1.1,
|
|
217
|
-
with
|
|
218
|
-
_validate_input_int([1],
|
|
219
|
-
with
|
|
220
|
-
_validate_input_int("1",
|
|
198
|
+
with pytest.raises(TypeError):
|
|
199
|
+
_validate_input_int(1.1, "No description")
|
|
200
|
+
with pytest.raises(TypeError):
|
|
201
|
+
_validate_input_int([1], "No description")
|
|
202
|
+
with pytest.raises(TypeError):
|
|
203
|
+
_validate_input_int("1", "No description")
|
|
221
204
|
|
|
222
|
-
def test__validate_input_smaller(self):
|
|
205
|
+
def test__validate_input_smaller(self) -> None:
|
|
223
206
|
# Raises an exception if the first value is larger than the second
|
|
224
|
-
with
|
|
225
|
-
_validate_input_smaller(0.3, 0.2,
|
|
226
|
-
with
|
|
227
|
-
_validate_input_smaller(3, 2,
|
|
228
|
-
with
|
|
229
|
-
_validate_input_smaller(5, -3,
|
|
207
|
+
with pytest.raises(ValueError, match="The first input for 'some check' should"):
|
|
208
|
+
_validate_input_smaller(0.3, 0.2, "some check")
|
|
209
|
+
with pytest.raises(ValueError, match="The first input for 'some check' should"):
|
|
210
|
+
_validate_input_smaller(3, 2, "some check")
|
|
211
|
+
with pytest.raises(ValueError, match="The first input for 'some check' should"):
|
|
212
|
+
_validate_input_smaller(5, -3, "some check")
|
|
230
213
|
|
|
231
|
-
def test__validate_input_range(self):
|
|
232
|
-
with
|
|
233
|
-
|
|
214
|
+
def test__validate_input_range(self) -> None:
|
|
215
|
+
with pytest.raises(
|
|
216
|
+
ValueError,
|
|
217
|
+
match="'actual' = -0.1 but should be 0 <= 'actual' <= 1.",
|
|
218
|
+
):
|
|
219
|
+
_validate_input_range(-0.1, "actual", 0, 1)
|
|
234
220
|
|
|
235
|
-
with
|
|
236
|
-
|
|
221
|
+
with pytest.raises(
|
|
222
|
+
ValueError,
|
|
223
|
+
match="'actual' = 1.1 but should be 0 <= 'actual' <= 1.",
|
|
224
|
+
):
|
|
225
|
+
_validate_input_range(1.1, "actual", 0, 1)
|
|
237
226
|
|
|
238
|
-
with
|
|
227
|
+
with pytest.raises(TypeError):
|
|
239
228
|
_validate_input_range("1", "value string", 0, 1)
|
|
240
229
|
|
|
241
|
-
def test__validate_input_sum_smaller(self):
|
|
242
|
-
with
|
|
230
|
+
def test__validate_input_sum_smaller(self) -> None:
|
|
231
|
+
with pytest.raises(
|
|
232
|
+
ValueError,
|
|
233
|
+
match="The sum of input values for 'Test Sum <= 1' should be less or equal to 1.",
|
|
234
|
+
):
|
|
243
235
|
_validate_input_sum_smaller(1, "Test Sum <= 1", 1.01)
|
|
244
|
-
with
|
|
236
|
+
with pytest.raises(
|
|
237
|
+
ValueError,
|
|
238
|
+
match="The sum of input values for 'Test Sum <= 1' should be less or equal to 1.",
|
|
239
|
+
):
|
|
245
240
|
_validate_input_sum_smaller(1, "Test Sum <= 1", 0.3, 0.2, 0.4, 0.5)
|
|
246
|
-
with
|
|
241
|
+
with pytest.raises(
|
|
242
|
+
ValueError,
|
|
243
|
+
match="The sum of input values for 'Test Sum <= -1' should be less or equal to -1.",
|
|
244
|
+
):
|
|
247
245
|
_validate_input_sum_smaller(-1, "Test Sum <= -1", -0.2, -0.7)
|
|
248
|
-
with
|
|
246
|
+
with pytest.raises(
|
|
247
|
+
ValueError,
|
|
248
|
+
match="The sum of input values for 'Test Sum <= 10' should be less or equal to 10.",
|
|
249
|
+
):
|
|
249
250
|
_validate_input_sum_smaller(10, "Test Sum <= 10", 20, -11, 2)
|
|
250
251
|
|
|
251
|
-
def test__validate_input_sum_larger(self):
|
|
252
|
-
with
|
|
252
|
+
def test__validate_input_sum_larger(self) -> None:
|
|
253
|
+
with pytest.raises(
|
|
254
|
+
ValueError,
|
|
255
|
+
match="The sum of input values for 'Test Sum >= 1' should be larger/equal to 1.",
|
|
256
|
+
):
|
|
253
257
|
_validate_input_sum_larger(1, "Test Sum >= 1", 0.99)
|
|
254
|
-
with
|
|
258
|
+
with pytest.raises(
|
|
259
|
+
ValueError,
|
|
260
|
+
match="The sum of input values for 'Test Sum >= 1' should be larger/equal to 1.",
|
|
261
|
+
):
|
|
255
262
|
_validate_input_sum_larger(1, "Test Sum >= 1", 0.9, 0.05)
|
|
256
|
-
with
|
|
263
|
+
with pytest.raises(
|
|
264
|
+
ValueError,
|
|
265
|
+
match="The sum of input values for 'Test Sum >=-2' should be larger/equal to -2.",
|
|
266
|
+
):
|
|
257
267
|
_validate_input_sum_larger(-2, "Test Sum >=-2", -3)
|
|
258
|
-
with
|
|
268
|
+
with pytest.raises(
|
|
269
|
+
ValueError,
|
|
270
|
+
match="The sum of input values for 'Test Sum >= 7' should be larger/equal to 7.",
|
|
271
|
+
):
|
|
259
272
|
_validate_input_sum_larger(7, "Test Sum >= 7", 1, 2, 3)
|
|
260
273
|
|
|
261
|
-
def test__validate_input_num_data(self):
|
|
262
|
-
with
|
|
263
|
-
_validate_input_num_data(
|
|
274
|
+
def test__validate_input_num_data(self) -> None:
|
|
275
|
+
with pytest.raises(TypeError):
|
|
276
|
+
_validate_input_num_data(
|
|
277
|
+
pd.DataFrame({"col1": ["a", "b", "c"]}),
|
|
278
|
+
"No description",
|
|
279
|
+
)
|
|
264
280
|
|
|
265
281
|
_validate_input_num_data(
|
|
266
282
|
pd.DataFrame({"col1": [1, 2, 3]}),
|
|
267
|
-
|
|
283
|
+
"No description",
|
|
268
284
|
) # No exception
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|