klib 1.4.0__tar.gz → 1.5.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.
Files changed (47) hide show
  1. {klib-1.4.0 → klib-1.5.0}/PKG-INFO +14 -8
  2. {klib-1.4.0 → klib-1.5.0}/README.md +1 -1
  3. {klib-1.4.0 → klib-1.5.0}/pyproject.toml +22 -10
  4. {klib-1.4.0 → klib-1.5.0}/src/klib/_version.py +1 -1
  5. {klib-1.4.0 → klib-1.5.0}/src/klib/clean.py +27 -13
  6. {klib-1.4.0 → klib-1.5.0}/src/klib/describe.py +63 -38
  7. {klib-1.4.0 → klib-1.5.0}/src/klib/utils.py +1 -1
  8. klib-1.5.0/tests/conftest.py +5 -0
  9. {klib-1.4.0 → klib-1.5.0}/tests/test_clean.py +40 -23
  10. {klib-1.4.0 → klib-1.5.0}/tests/test_describe.py +79 -0
  11. klib-1.4.0/.github/FUNDING.yml +0 -3
  12. klib-1.4.0/.github/ISSUE_TEMPLATE/bug_report.md +0 -32
  13. klib-1.4.0/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  14. klib-1.4.0/.github/dependabot.yml +0 -11
  15. klib-1.4.0/.github/workflows/codeql-analysis.yml +0 -49
  16. klib-1.4.0/.github/workflows/pre-commit.yaml +0 -19
  17. klib-1.4.0/.github/workflows/pythonpackage.yml +0 -74
  18. klib-1.4.0/.pre-commit-config.yaml +0 -47
  19. klib-1.4.0/CODE_OF_CONDUCT.md +0 -128
  20. klib-1.4.0/MANIFEST.in +0 -1
  21. klib-1.4.0/Makefile +0 -19
  22. klib-1.4.0/examples/NFL_DATASET.csv +0 -4
  23. klib-1.4.0/examples/datasets/.gitignore +0 -1
  24. klib-1.4.0/examples/images/example_cat_plot.png +0 -0
  25. klib-1.4.0/examples/images/example_corr_interactive_plot.png +0 -0
  26. klib-1.4.0/examples/images/example_corr_plot.png +0 -0
  27. klib-1.4.0/examples/images/example_dist_plot.png +0 -0
  28. klib-1.4.0/examples/images/example_klib_corr_mat.png +0 -0
  29. klib-1.4.0/examples/images/example_klib_data_cleaning_dtypes.png +0 -0
  30. klib-1.4.0/examples/images/example_klib_data_cleaning_report.png +0 -0
  31. klib-1.4.0/examples/images/example_klib_pool_duplicate_subsets1.png +0 -0
  32. klib-1.4.0/examples/images/example_klib_pool_duplicate_subsets2.png +0 -0
  33. klib-1.4.0/examples/images/example_klib_pool_duplicate_subsets3.png +0 -0
  34. klib-1.4.0/examples/images/example_mv_plot.png +0 -0
  35. klib-1.4.0/examples/images/example_target_corr_plot.png +0 -0
  36. klib-1.4.0/examples/images/header.png +0 -0
  37. klib-1.4.0/examples/klib-plots.ipynb +0 -2780
  38. klib-1.4.0/examples/klib_data_cleaning.ipynb +0 -796
  39. klib-1.4.0/uv.lock +0 -2546
  40. {klib-1.4.0 → klib-1.5.0}/.gitignore +0 -0
  41. {klib-1.4.0 → klib-1.5.0}/LICENSE +0 -0
  42. {klib-1.4.0 → klib-1.5.0}/examples/README.md +0 -0
  43. {klib-1.4.0 → klib-1.5.0}/src/klib/__init__.py +0 -0
  44. {klib-1.4.0 → klib-1.5.0}/src/klib/scripts/__init__.py +0 -0
  45. {klib-1.4.0 → klib-1.5.0}/src/klib/scripts/performance.py +0 -0
  46. {klib-1.4.0 → klib-1.5.0}/tests/__init__.py +0 -0
  47. {klib-1.4.0 → klib-1.5.0}/tests/test_util.py +0 -0
@@ -1,18 +1,24 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: klib
3
- Version: 1.4.0
3
+ Version: 1.5.0
4
4
  Summary: Common data preprocessing and visualisation functions.
5
- Author-email: Andreas Kanz <andreas@akanz.de>
5
+ Project-URL: Homepage, https://github.com/akanz1/klib
6
+ Project-URL: Issues, https://github.com/akanz1/klib/issues
7
+ Author: Andreas Kanz
6
8
  License-Expression: MIT
7
9
  License-File: LICENSE
8
- Classifier: License :: OSI Approved :: MIT License
9
10
  Classifier: Operating System :: OS Independent
10
11
  Classifier: Programming Language :: Python :: 3
11
- Requires-Python: >=3.10
12
- Requires-Dist: jinja2>=3.1.0
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: jinja2>=3.1.2
13
19
  Requires-Dist: matplotlib>=3.9.0
14
20
  Requires-Dist: numpy>=2.0.0
15
- Requires-Dist: pandas<4.0,>=1.4
21
+ Requires-Dist: pandas<4.0,>=2.2.2
16
22
  Requires-Dist: plotly>=5.24.0
17
23
  Requires-Dist: scipy>=1.14.0
18
24
  Requires-Dist: screeninfo>=0.8.1
@@ -21,7 +27,7 @@ Description-Content-Type: text/markdown
21
27
 
22
28
  <p align="center"><img src="https://raw.githubusercontent.com/akanz1/klib/main/examples/images/header.png" alt="klib Header" width="859" height="304"></p>
23
29
 
24
- [![Flake8 & PyTest](https://github.com/akanz1/klib/workflows/Flake8%20%F0%9F%90%8D%20PyTest%20%20%20%C2%B4/badge.svg)](https://github.com/akanz1/klib)
30
+ [![Ruff & Pytest](https://github.com/akanz1/klib/actions/workflows/pythonpackage.yml/badge.svg)](https://github.com/akanz1/klib/actions/workflows/pythonpackage.yml)
25
31
  [![Language](https://img.shields.io/github/languages/top/akanz1/klib)](https://pypi.org/project/klib/)
26
32
  [![Last Commit](https://badgen.net/github/last-commit/akanz1/klib/main)](https://github.com/akanz1/klib/commits/main)
27
33
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=akanz1_klib&metric=alert_status)](https://sonarcloud.io/dashboard?id=akanz1_klib)
@@ -1,6 +1,6 @@
1
1
  <p align="center"><img src="https://raw.githubusercontent.com/akanz1/klib/main/examples/images/header.png" alt="klib Header" width="859" height="304"></p>
2
2
 
3
- [![Flake8 & PyTest](https://github.com/akanz1/klib/workflows/Flake8%20%F0%9F%90%8D%20PyTest%20%20%20%C2%B4/badge.svg)](https://github.com/akanz1/klib)
3
+ [![Ruff & Pytest](https://github.com/akanz1/klib/actions/workflows/pythonpackage.yml/badge.svg)](https://github.com/akanz1/klib/actions/workflows/pythonpackage.yml)
4
4
  [![Language](https://img.shields.io/github/languages/top/akanz1/klib)](https://pypi.org/project/klib/)
5
5
  [![Last Commit](https://badgen.net/github/last-commit/akanz1/klib/main)](https://github.com/akanz1/klib/commits/main)
6
6
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=akanz1_klib&metric=alert_status)](https://sonarcloud.io/dashboard?id=akanz1_klib)
@@ -1,28 +1,36 @@
1
1
  [project]
2
2
  name = "klib"
3
- version = "1.4.0"
3
+ version = "1.5.0"
4
4
  description = "Common data preprocessing and visualisation functions."
5
- authors = [{ name = "Andreas Kanz", email = "andreas@akanz.de" }]
5
+ authors = [{ name = "Andreas Kanz" }]
6
6
  license = "MIT"
7
7
  readme = "README.md"
8
- requires-python = ">=3.10"
8
+ requires-python = ">=3.11"
9
9
  classifiers = [
10
10
  "Programming Language :: Python :: 3",
11
- "License :: OSI Approved :: MIT License",
11
+ "Programming Language :: Python :: 3.11",
12
+ "Programming Language :: Python :: 3.12",
13
+ "Programming Language :: Python :: 3.13",
14
+ "Programming Language :: Python :: 3.14",
15
+ "Programming Language :: Python :: 3.15",
12
16
  "Operating System :: OS Independent",
13
17
  ]
14
18
 
15
19
  dependencies = [
16
- "Jinja2 >= 3.1.0",
20
+ "Jinja2 >= 3.1.2",
17
21
  "matplotlib >= 3.9.0",
18
22
  "numpy >= 2.0.0",
19
- "pandas >=1.4,<4.0",
23
+ "pandas >=2.2.2,<4.0",
20
24
  "plotly >= 5.24.0",
21
25
  "scipy >= 1.14.0",
22
26
  "screeninfo >= 0.8.1",
23
27
  "seaborn >=0.13.0",
24
28
  ]
25
29
 
30
+ [project.urls]
31
+ Homepage = "https://github.com/akanz1/klib"
32
+ Issues = "https://github.com/akanz1/klib/issues"
33
+
26
34
  [dependency-groups]
27
35
  dev = [
28
36
  "ipykernel >=6.29.5",
@@ -39,6 +47,9 @@ dev = [
39
47
  requires = ["hatchling"]
40
48
  build-backend = "hatchling.build"
41
49
 
50
+ [tool.hatch.build.targets.sdist]
51
+ include = ["src/klib", "tests", "README.md", "LICENSE"]
52
+
42
53
  [tool.pydocstyle]
43
54
  match_dir = "[^(?!tests|\\.)].*" # not tests and not a folder that starts with a dot
44
55
  match = "^(?!(__init__|setup)).*py$" # py files which do not start with __init__ or setup
@@ -65,7 +76,7 @@ branch = true
65
76
  data_file = "tests/.coverage"
66
77
 
67
78
  [tool.coverage.report]
68
- fail_skip_covered = true
79
+ skip_covered = true
69
80
  exclude_also = [
70
81
  "if self.debug:",
71
82
  "if settings.DEBUG",
@@ -82,7 +93,7 @@ exclude_also = [
82
93
 
83
94
  [tool.ruff]
84
95
  line-length = 100
85
- target-version = "py313"
96
+ target-version = "py311"
86
97
  fix = true
87
98
 
88
99
  lint.select = ["ALL"]
@@ -108,8 +119,9 @@ lint.ignore = [
108
119
  "PLR0913",
109
120
  "D213",
110
121
  "D203",
111
- "UP038",
112
- "PD901",
122
+ "RUF043",
123
+ "CPY001",
124
+ "PLR0917",
113
125
  ]
114
126
 
115
127
  extend-exclude = ["examples"]
@@ -1,3 +1,3 @@
1
1
  """Current version of klib."""
2
2
 
3
- __version__ = "1.4.0"
3
+ __version__ = "1.5.0"
@@ -11,6 +11,8 @@ from typing import Literal
11
11
 
12
12
  import numpy as np
13
13
  import pandas as pd
14
+ from pandas.api.types import is_bool_dtype
15
+ from pandas.api.types import is_numeric_dtype
14
16
 
15
17
  from klib.describe import corr_mat
16
18
  from klib.utils import _diff_report
@@ -107,13 +109,11 @@ def clean_column_names(data: pd.DataFrame, *, hints: bool = True) -> pd.DataFram
107
109
  col if col not in data.columns[:i] else f"{col}_{i!s}"
108
110
  for i, col in enumerate(data.columns)
109
111
  ]
110
- print_statement = ""
111
112
  if hints:
112
- # add string to print statement
113
113
  print_statement = (
114
114
  f"Duplicate column names detected! Columns with index {dupl_idx} and "
115
115
  f"names {dupl_before} have been renamed to "
116
- f"{data.columns[dupl_idx].tolist()}.",
116
+ f"{data.columns[dupl_idx].tolist()}."
117
117
  )
118
118
 
119
119
  if long_col_names := [
@@ -122,8 +122,8 @@ def clean_column_names(data: pd.DataFrame, *, hints: bool = True) -> pd.DataFram
122
122
  if len(x) > 25 # noqa: PLR2004
123
123
  ]:
124
124
  print_statement += (
125
- "Long column names detected (>25 characters). Consider renaming "
126
- f"the following columns {long_col_names}.",
125
+ " Long column names detected (>25 characters). Consider renaming "
126
+ f"the following columns {long_col_names}."
127
127
  )
128
128
 
129
129
  print(print_statement)
@@ -139,8 +139,8 @@ def convert_datatypes(
139
139
  ) -> pd.DataFrame:
140
140
  """Convert columns to best possible dtypes using dtypes supporting pd.NA.
141
141
 
142
- Temporarily not converting to integers due to an issue in pandas. This is expected \
143
- to be fixed in pandas 1.1. See https://github.com/pandas-dev/pandas/issues/33803
142
+ Numeric columns keep their NumPy dtypes; other columns are converted to nullable \
143
+ dtypes such as "string" or "boolean".
144
144
 
145
145
  Parameters
146
146
  ----------
@@ -169,12 +169,21 @@ def convert_datatypes(
169
169
 
170
170
  data = pd.DataFrame(data).copy()
171
171
 
172
- # First pass: convert dtypes to get StringDtype, etc.
172
+ # First pass: convert dtypes to get StringDtype, etc. Numeric columns keep their
173
+ # dtypes, as with the deprecated convert_integer/convert_floating=False keywords.
173
174
  for col in data.columns:
174
- data[col] = data[col].convert_dtypes(
175
- convert_integer=False,
176
- convert_floating=False,
177
- )
175
+ series = data[col].infer_objects()
176
+ if is_numeric_dtype(series) and not is_bool_dtype(series):
177
+ data[col] = series
178
+ continue
179
+ try:
180
+ converted = series.convert_dtypes()
181
+ except OverflowError: # pandas < 3 cannot fit ints beyond the int64 range
182
+ converted = series
183
+ if is_numeric_dtype(converted) and not is_bool_dtype(converted):
184
+ data[col] = series
185
+ else:
186
+ data[col] = converted
178
187
 
179
188
  # Second pass: check for categorical conversion on string/object columns
180
189
  for col in data.columns:
@@ -371,6 +380,11 @@ def data_cleaning(
371
380
  cat_threshold=cat_threshold,
372
381
  cat_exclude=cat_exclude,
373
382
  )
383
+ else:
384
+ string_cols = [
385
+ col for col in data_cleaned.columns if data_cleaned[col].dtype.name in ("str", "string")
386
+ ]
387
+ data_cleaned[string_cols] = data_cleaned[string_cols].astype("object")
374
388
 
375
389
  _diff_report(
376
390
  data,
@@ -450,7 +464,7 @@ def mv_col_handling(
450
464
  data_local = data.copy()
451
465
  mv_ratios = _missing_vals(data_local)["mv_cols_ratio"]
452
466
  cols_mv = mv_ratios[mv_ratios > mv_threshold].index.tolist()
453
- data_local[cols_mv] = data_local[cols_mv].map(lambda x: x if pd.isna(x) else 1).fillna(0)
467
+ data_local[cols_mv] = data_local[cols_mv].notna().astype(int)
454
468
 
455
469
  high_corr_features = []
456
470
  data_temp = data_local.copy()
@@ -89,7 +89,7 @@ def cat_plot( # noqa: C901, PLR0915
89
89
  return None
90
90
 
91
91
  for col in data.columns:
92
- if data[col].dtype.name in ("category", "string"):
92
+ if data[col].dtype.name in ("category", "str", "string"):
93
93
  data[col] = data[col].astype("object")
94
94
 
95
95
  fig = plt.figure(figsize=figsize)
@@ -272,7 +272,13 @@ def corr_mat(
272
272
  corr = _corr_selector(corr, split=split, threshold=threshold)
273
273
 
274
274
  if colored:
275
- return corr.style.map(color_negative_red).format("{:.2f}", na_rep="-")
275
+ styler = corr.style
276
+ styler = (
277
+ styler.map(color_negative_red)
278
+ if hasattr(styler, "map")
279
+ else styler.applymap(color_negative_red)
280
+ )
281
+ return styler.format("{:.2f}", na_rep="-")
276
282
  return corr
277
283
 
278
284
 
@@ -287,6 +293,7 @@ def corr_plot(
287
293
  *,
288
294
  annot: bool = True,
289
295
  dev: bool = False,
296
+ ax: plt.Axes | None = None,
290
297
  **kwargs, # noqa: ANN003
291
298
  ) -> plt.Axes:
292
299
  """2D visualization of the correlation between feature-columns excluding NA values.
@@ -334,6 +341,8 @@ def corr_plot(
334
341
  dev : bool, optional
335
342
  Display figure settings in the plot by setting dev = True. If False, the \
336
343
  settings are not displayed, by default False
344
+ ax : matplotlib Axes, optional
345
+ Existing Axes object to draw into, by default None.
337
346
 
338
347
  kwargs : optional
339
348
  Additional elements to control the visualization of the plot, e.g.:
@@ -389,7 +398,10 @@ def corr_plot(
389
398
  vmax = np.round(np.nanmax(corr.where(~mask)) - 0.05, 2)
390
399
  vmin = np.round(np.nanmin(corr.where(~mask)) + 0.05, 2)
391
400
 
392
- fig, ax = plt.subplots(figsize=figsize)
401
+ if ax is None:
402
+ fig, ax = plt.subplots(figsize=figsize)
403
+ else:
404
+ fig = ax.figure
393
405
 
394
406
  # Specify kwargs for the heatmap
395
407
  kwargs = {
@@ -401,6 +413,7 @@ def corr_plot(
401
413
  "linewidths": 0.5,
402
414
  "annot_kws": {"size": 10},
403
415
  "cbar_kws": {"shrink": 0.95, "aspect": 30},
416
+ "ax": ax,
404
417
  **kwargs,
405
418
  }
406
419
 
@@ -586,7 +599,7 @@ def corr_interactive_plot( # noqa: C901
586
599
 
587
600
  if target is None:
588
601
  mask = np.triu(np.ones_like(corr, dtype=bool))
589
- np.fill_diagonal(corr.to_numpy(), np.nan)
602
+ corr = corr.mask(np.eye(len(corr), dtype=bool))
590
603
  corr = corr.where(mask == 1)
591
604
  else:
592
605
  corr = corr.iloc[::-1, :]
@@ -597,7 +610,7 @@ def corr_interactive_plot( # noqa: C901
597
610
  vmax = -vmin if split == "neg" else vmax
598
611
  vmin = -vmax if split == "pos" else vmin
599
612
 
600
- vtext = corr.round(2).fillna("") if annot else None
613
+ vtext = corr.round(2).astype(object).fillna("") if annot else None
601
614
 
602
615
  corr_columns = corr.columns
603
616
  corr_index = corr.index
@@ -663,7 +676,7 @@ def corr_interactive_plot( # noqa: C901
663
676
  return heatmap
664
677
 
665
678
 
666
- def dist_plot(
679
+ def dist_plot( # noqa: PLR0915
667
680
  data: pd.DataFrame,
668
681
  mean_color: str = "orange",
669
682
  size: int = 3,
@@ -673,7 +686,8 @@ def dist_plot(
673
686
  rug_kws: dict[str, Any] | None = None,
674
687
  fill_kws: dict[str, Any] | None = None,
675
688
  font_kws: dict[str, Any] | None = None,
676
- ) -> None | Any: # noqa: ANN401
689
+ ax: plt.Axes | None = None,
690
+ ) -> Any | None: # noqa: ANN401
677
691
  """2D visualization of the distribution of non binary numerical features.
678
692
 
679
693
  Parameters
@@ -702,6 +716,8 @@ def dist_plot(
702
716
  font_kws : dict[str, Any], optional
703
717
  Keyword arguments to control the font, by default {"color": "#111111", \
704
718
  "weight": "normal", "size": 11}
719
+ ax : matplotlib Axes, optional
720
+ Existing Axes object to draw a single numeric column into, by default None.
705
721
 
706
722
  Returns
707
723
  -------
@@ -757,25 +773,34 @@ def dist_plot(
757
773
  if not cols:
758
774
  print("No columns with numeric data were detected.")
759
775
  return None
776
+ if ax is not None and len(cols) != 1:
777
+ msg = "When ax is provided, dist_plot requires exactly one numeric non-binary column."
778
+ raise ValueError(msg)
760
779
 
761
780
  for col in cols:
762
781
  col_data = data[col].dropna(axis=0)
763
782
  col_df = df[col].dropna(axis=0)
764
783
 
765
- g = sns.displot(
766
- col_data,
767
- kind="kde",
768
- rug=True,
769
- height=size,
770
- aspect=5,
771
- legend=False,
772
- rug_kws=rug_kws,
773
- **kde_kws,
774
- )
784
+ if ax is None:
785
+ g = sns.displot(
786
+ col_data,
787
+ kind="kde",
788
+ rug=True,
789
+ height=size,
790
+ aspect=5,
791
+ legend=False,
792
+ rug_kws=rug_kws,
793
+ **kde_kws,
794
+ )
795
+ plot_ax = g.axes[0, 0]
796
+ else:
797
+ sns.kdeplot(col_data, ax=ax, **kde_kws)
798
+ sns.rugplot(col_data, ax=ax, **rug_kws)
799
+ plot_ax = ax
775
800
 
776
801
  # Vertical lines and fill
777
- x, y = g.axes[0, 0].lines[0].get_xydata().T
778
- g.axes[0, 0].fill_between(
802
+ x, y = plot_ax.lines[0].get_xydata().T
803
+ plot_ax.fill_between(
779
804
  x,
780
805
  y,
781
806
  where=(
@@ -788,7 +813,7 @@ def dist_plot(
788
813
 
789
814
  mean = np.mean(col_df)
790
815
  std = scipy.stats.tstd(col_df)
791
- g.axes[0, 0].vlines(
816
+ plot_ax.vlines(
792
817
  x=mean,
793
818
  ymin=0,
794
819
  ymax=np.interp(mean, x, y),
@@ -797,7 +822,7 @@ def dist_plot(
797
822
  lw=2,
798
823
  label="mean",
799
824
  )
800
- g.axes[0, 0].vlines(
825
+ plot_ax.vlines(
801
826
  x=np.median(col_df),
802
827
  ymin=0,
803
828
  ymax=np.interp(np.median(col_df), x, y),
@@ -805,7 +830,7 @@ def dist_plot(
805
830
  color=".3",
806
831
  label="median",
807
832
  )
808
- g.axes[0, 0].vlines(
833
+ plot_ax.vlines(
809
834
  x=[mean - std, mean + std],
810
835
  ymin=0,
811
836
  ymax=[np.interp(mean - std, x, y), np.interp(mean + std, x, y)],
@@ -814,51 +839,51 @@ def dist_plot(
814
839
  label="\u03bc \u00b1 \u03c3",
815
840
  )
816
841
 
817
- g.axes[0, 0].set_ylim(0)
818
- g.axes[0, 0].set_xlim(
819
- g.axes[0, 0].get_xlim()[0] - g.axes[0, 0].get_xlim()[1] * 0.05,
820
- g.axes[0, 0].get_xlim()[1] * 1.03,
842
+ plot_ax.set_ylim(0)
843
+ plot_ax.set_xlim(
844
+ plot_ax.get_xlim()[0] - plot_ax.get_xlim()[1] * 0.05,
845
+ plot_ax.get_xlim()[1] * 1.03,
821
846
  )
822
847
 
823
848
  # Annotations and legend
824
- g.axes[0, 0].text(
849
+ plot_ax.text(
825
850
  0.005,
826
851
  0.9,
827
852
  f"Mean: {mean:.2f}",
828
853
  fontdict=font_kws,
829
- transform=g.axes[0, 0].transAxes,
854
+ transform=plot_ax.transAxes,
830
855
  )
831
- g.axes[0, 0].text(
856
+ plot_ax.text(
832
857
  0.005,
833
858
  0.7,
834
859
  f"Std. dev: {std:.2f}",
835
860
  fontdict=font_kws,
836
- transform=g.axes[0, 0].transAxes,
861
+ transform=plot_ax.transAxes,
837
862
  )
838
- g.axes[0, 0].text(
863
+ plot_ax.text(
839
864
  0.005,
840
865
  0.5,
841
866
  f"Skew: {scipy.stats.skew(col_df):.2f}",
842
867
  fontdict=font_kws,
843
- transform=g.axes[0, 0].transAxes,
868
+ transform=plot_ax.transAxes,
844
869
  )
845
- g.axes[0, 0].text(
870
+ plot_ax.text(
846
871
  0.005,
847
872
  0.3,
848
873
  f"Kurtosis: {scipy.stats.kurtosis(col_df):.2f}", # Excess Kurtosis
849
874
  fontdict=font_kws,
850
- transform=g.axes[0, 0].transAxes,
875
+ transform=plot_ax.transAxes,
851
876
  )
852
- g.axes[0, 0].text(
877
+ plot_ax.text(
853
878
  0.005,
854
879
  0.1,
855
880
  f"Count: {len(col_df)}",
856
881
  fontdict=font_kws,
857
- transform=g.axes[0, 0].transAxes,
882
+ transform=plot_ax.transAxes,
858
883
  )
859
- g.axes[0, 0].legend(loc="upper right")
884
+ plot_ax.legend(loc="upper right")
860
885
 
861
- return g.axes[0, 0]
886
+ return plot_ax
862
887
 
863
888
 
864
889
  def missingval_plot( # noqa: PLR0915
@@ -140,7 +140,7 @@ def _diff_report(
140
140
  )
141
141
  print(f"Dropped missing values: {data_mv_tot - data_cl_mv_tot}")
142
142
  mem_change = data_mem - data_cl_mem
143
- mem_perc = round(100 * mem_change / data_mem, 2)
143
+ mem_perc = round(100 * mem_change / data_mem, 2) if data_mem else 0
144
144
  print(f"Reduced memory by at least: {round(mem_change, 3)} MB (-{mem_perc}%)\n")
145
145
 
146
146
 
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ import matplotlib as mpl
4
+
5
+ mpl.use("Agg")
@@ -68,7 +68,7 @@ class Test_clean_column_names(unittest.TestCase):
68
68
  clean_column_names(self.df_clean_column_names, hints=True)
69
69
  sys.stdout = sys.__stdout__
70
70
  assert captured_output.getvalue() == (
71
- "(\"Duplicate column names detected! Columns with index [7, 8] and names ['dupli', 'also'] have been renamed to ['dupli_7', 'also_8'].\", \"Long column names detected (>25 characters). Consider renaming the following columns ['ae_some_plus_plus_dollar_percent_name', 'verylong_column_namesare_hardto_read'].\")\n"
71
+ "Duplicate column names detected! Columns with index [7, 8] and names ['dupli', 'also'] have been renamed to ['dupli_7', 'also_8']. Long column names detected (>25 characters). Consider renaming the following columns ['ae_some_plus_plus_dollar_percent_name', 'verylong_column_namesare_hardto_read'].\n"
72
72
  )
73
73
 
74
74
 
@@ -160,28 +160,24 @@ class Test_data_cleaning(unittest.TestCase):
160
160
 
161
161
  expected_results = ["string", "float32", "object", "object"]
162
162
  for i, _ in enumerate(expected_results):
163
- result_dtype = data_cleaning(self.df_data_cleaning, convert_dtypes=True).dtypes.iloc[i]
164
- assert result_dtype.name == expected_results[i]
163
+ assert (
164
+ data_cleaning(self.df_data_cleaning, convert_dtypes=True).dtypes.iloc[i]
165
+ == expected_results[i]
166
+ )
165
167
 
166
- expected_results = [
167
- ["str", "string", "object"],
168
- ["object"],
169
- ["object"],
170
- ["object"],
171
- ]
172
- for i, allowed in enumerate(expected_results):
173
- result_dtype = data_cleaning(self.df_data_cleaning, convert_dtypes=False).dtypes.iloc[i]
174
- assert result_dtype.name in allowed
168
+ expected_results = ["O", "O", "O", "O"]
169
+ for i, _ in enumerate(expected_results):
170
+ assert (
171
+ data_cleaning(self.df_data_cleaning, convert_dtypes=False).dtypes.iloc[i]
172
+ == expected_results[i]
173
+ )
175
174
 
176
- expected_results = [
177
- ["str", "string", "object"],
178
- ["object"],
179
- ["object"],
180
- ["object"],
181
- ]
182
- for i, allowed in enumerate(expected_results):
183
- result_dtype = data_cleaning(self.df_data_cleaning, convert_dtypes=False).dtypes.iloc[i]
184
- assert result_dtype.name in allowed
175
+ expected_results = ["O", "O", "O", "O"]
176
+ for i, _ in enumerate(expected_results):
177
+ assert (
178
+ data_cleaning(self.df_data_cleaning, convert_dtypes=False).dtypes.iloc[i]
179
+ == expected_results[i]
180
+ )
185
181
 
186
182
 
187
183
  class Test_convert_dtypes(unittest.TestCase):
@@ -208,8 +204,10 @@ class Test_convert_dtypes(unittest.TestCase):
208
204
  "category",
209
205
  ]
210
206
  for i, _ in enumerate(expected_results):
211
- result_dtype = convert_datatypes(self.df_data_convert, cat_threshold=0.4).dtypes.iloc[i]
212
- assert result_dtype.name == expected_results[i]
207
+ assert (
208
+ convert_datatypes(self.df_data_convert, cat_threshold=0.4).dtypes[i]
209
+ == expected_results[i]
210
+ )
213
211
 
214
212
  expected_results = [
215
213
  "int8",
@@ -265,6 +263,25 @@ class Test_convert_dtypes(unittest.TestCase):
265
263
  ).dtypes.iloc[i]
266
264
  assert result_dtype.name == expected_results[i]
267
265
 
266
+ def test_convert_dtypes_object_numbers_with_na(self) -> None:
267
+ data = pd.DataFrame(
268
+ {
269
+ "ints": pd.Series([1, 2, pd.NA], dtype=object),
270
+ "floats": pd.Series([1.5, 2.5, pd.NA], dtype=object),
271
+ "bools": pd.Series([True, False, pd.NA], dtype=object),
272
+ "big_ints": pd.Series([2**63, 2**53 + 1, pd.NA], dtype=object),
273
+ "complex": pd.Series([1 + 2j, 3 + 4j, np.nan]),
274
+ },
275
+ )
276
+ result = convert_datatypes(data, category=False)
277
+ assert result["ints"].dtype.name == "object"
278
+ assert result["floats"].dtype.name == "object"
279
+ assert result["bools"].dtype.name == "boolean"
280
+ assert result["big_ints"].dtype.name == "object"
281
+ assert result["big_ints"].iloc[:2].tolist() == [2**63, 2**53 + 1]
282
+ assert result["big_ints"].isna().tolist() == [False, False, True]
283
+ assert result["complex"].dtype.name == "complex128"
284
+
268
285
 
269
286
  class Test_pool_duplicate_subsets(unittest.TestCase):
270
287
  @classmethod