kryzokit 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.
- kryzokit-0.1.0/LICENSE +21 -0
- kryzokit-0.1.0/PKG-INFO +150 -0
- kryzokit-0.1.0/README.md +127 -0
- kryzokit-0.1.0/kryzokit/__init__.py +24 -0
- kryzokit-0.1.0/kryzokit/_utils.py +39 -0
- kryzokit-0.1.0/kryzokit/cleaning.py +144 -0
- kryzokit-0.1.0/kryzokit/datasets.py +39 -0
- kryzokit-0.1.0/kryzokit/encoding.py +29 -0
- kryzokit-0.1.0/kryzokit/pipeline.py +209 -0
- kryzokit-0.1.0/kryzokit/plot.py +26 -0
- kryzokit-0.1.0/kryzokit/report.py +26 -0
- kryzokit-0.1.0/kryzokit/split.py +46 -0
- kryzokit-0.1.0/kryzokit/transform.py +29 -0
- kryzokit-0.1.0/kryzokit.egg-info/PKG-INFO +150 -0
- kryzokit-0.1.0/kryzokit.egg-info/SOURCES.txt +22 -0
- kryzokit-0.1.0/kryzokit.egg-info/dependency_links.txt +1 -0
- kryzokit-0.1.0/kryzokit.egg-info/requires.txt +8 -0
- kryzokit-0.1.0/kryzokit.egg-info/top_level.txt +1 -0
- kryzokit-0.1.0/pyproject.toml +32 -0
- kryzokit-0.1.0/setup.cfg +4 -0
- kryzokit-0.1.0/tests/test_cleaning.py +125 -0
- kryzokit-0.1.0/tests/test_pipeline.py +135 -0
- kryzokit-0.1.0/tests/test_split_report.py +64 -0
- kryzokit-0.1.0/tests/test_transform_encoding.py +63 -0
kryzokit-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kryzotech
|
|
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.
|
kryzokit-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kryzokit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Data preprocessing made easy: clean, scale, encode and split in a few lines
|
|
5
|
+
Author-email: Kryzotech <kryzotech@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/asif851/kryzokit-project
|
|
8
|
+
Keywords: preprocessing,pandas,machine-learning,data-cleaning,education
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Intended Audience :: Education
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: pandas>=1.5
|
|
16
|
+
Requires-Dist: numpy>=1.23
|
|
17
|
+
Requires-Dist: matplotlib>=3.5
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Requires-Dist: build; extra == "dev"
|
|
21
|
+
Requires-Dist: twine; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# kryzokit
|
|
25
|
+
|
|
26
|
+
**Data preprocessing made easy.** Clean, scale, encode and split a pandas table in a few readable lines,
|
|
27
|
+
so you can spend your time on the model instead of on boilerplate. Made for students and beginners.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import kryzokit as kp
|
|
31
|
+
|
|
32
|
+
X_train, X_test, y_train, y_test, prep = kp.prepare_data(df, "target")
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
That one line splits your data, fills missing values, scales the numbers and one-hot encodes the text,
|
|
36
|
+
learning everything from the **training rows only** (no data leakage).
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install kryzokit # after it is published on PyPI
|
|
42
|
+
pip install -e . # from this folder, while developing
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Needs Python 3.9+, pandas, numpy and matplotlib.
|
|
46
|
+
|
|
47
|
+
## Five-minute tour
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import kryzokit as kp
|
|
51
|
+
|
|
52
|
+
df = kp.sample_data() # a messy practice table
|
|
53
|
+
print(kp.overview(df)) # type, missing, unique values, example - for every column
|
|
54
|
+
kp.plot_missing(df) # chart of missing values
|
|
55
|
+
|
|
56
|
+
# safe clean-up steps
|
|
57
|
+
df = kp.clean_column_names(df) # ' Annual Income ($)' -> 'annual_income'
|
|
58
|
+
df = kp.strip_text(df) # 'Dhaka ' -> 'Dhaka'
|
|
59
|
+
df = kp.drop_duplicates(df)
|
|
60
|
+
|
|
61
|
+
# the whole ML preparation
|
|
62
|
+
X_train, X_test, y_train, y_test, prep = kp.prepare_data(df, "purchased", stratify=True)
|
|
63
|
+
|
|
64
|
+
# new data later? use the same preparation
|
|
65
|
+
X_new = prep.transform(new_rows)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## All functions
|
|
69
|
+
|
|
70
|
+
Every function returns a **new** table and never changes the one you give it.
|
|
71
|
+
|
|
72
|
+
| Group | Function | What it does |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| Look | `overview(df)` | One row per column: type, missing, unique values, example |
|
|
75
|
+
| | `missing_report(df)` | Missing count and percent per column, worst first |
|
|
76
|
+
| | `histogram(df, "col")`, `plot_missing(df)` | Quick charts (`show=False` to get the chart without opening a window) |
|
|
77
|
+
| Clean | `clean_column_names(df)` | Lowercase names with underscores |
|
|
78
|
+
| | `strip_text(df)` | Remove spaces around text |
|
|
79
|
+
| | `drop_duplicates(df)` | Remove repeated rows |
|
|
80
|
+
| Missing | `fill_missing(df, strategy="auto")` | `auto` (numbers: median, text: most common), `mean`, `median`, `mode`, `constant` |
|
|
81
|
+
| | `drop_missing_columns(df, threshold=0.5)` | Drop columns with too many empty cells |
|
|
82
|
+
| | `drop_missing_rows(df)` | Drop rows that have empty cells |
|
|
83
|
+
| Outliers | `clip_outliers(df, method="iqr")` | Pull extreme values back to the normal range (`iqr` or `zscore`) |
|
|
84
|
+
| | `remove_outliers(df, method="iqr")` | Drop rows with extreme values |
|
|
85
|
+
| Scale | `normalize(df)` | Min-max: values from 0 to 1 |
|
|
86
|
+
| | `standardize(df)` | Z-score: mean 0, standard deviation 1 |
|
|
87
|
+
| Encode | `label_encode(df)` | Category -> number (`return_mapping=True` shows which) |
|
|
88
|
+
| | `one_hot(df)` | One 0/1 column per category |
|
|
89
|
+
| Split | `train_test_split(df, "target")` | `X_train, X_test, y_train, y_test` (`stratify=True` keeps class shares) |
|
|
90
|
+
| One call | `quick_clean(df)` | Names + text + duplicates + missing values, all at once |
|
|
91
|
+
| | `Preprocessor(...)` | Learn on train data, apply to test/new data |
|
|
92
|
+
| | `prepare_data(df, "target")` | Split + `Preprocessor` in one line |
|
|
93
|
+
| Practice | `sample_data()` | A messy table with a 0/1 `Purchased` column |
|
|
94
|
+
|
|
95
|
+
## Preprocessor options
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
prep = kp.Preprocessor(
|
|
99
|
+
fill="auto", # "auto", "mean", "median", "mode" or None
|
|
100
|
+
scale="standard", # None, "minmax" or "standard"
|
|
101
|
+
encode="onehot", # None, "onehot" or "label"
|
|
102
|
+
outliers="iqr", # None, "iqr" or "zscore" (clips extreme numbers)
|
|
103
|
+
drop_missing_above=0.5, # drop columns with more than 50 % missing
|
|
104
|
+
)
|
|
105
|
+
X_train = prep.fit_transform(X_train) # learn from the training rows
|
|
106
|
+
X_test = prep.transform(X_test) # reuse exactly the same numbers
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Give it the **features only** (no target column). Unknown categories in new data become all zeros
|
|
110
|
+
(`onehot`) or `-1` (`label`).
|
|
111
|
+
|
|
112
|
+
## Important rule: learn from the training data only
|
|
113
|
+
|
|
114
|
+
Filling, scaling and encoding use numbers calculated from the data (a median, a mean, a list of
|
|
115
|
+
categories). If you calculate them on the **whole** table before splitting, information from the test
|
|
116
|
+
rows leaks into training and your test score looks better than it really is.
|
|
117
|
+
|
|
118
|
+
* Safe before splitting (they do not look at other rows): `clean_column_names`, `strip_text`, `drop_duplicates`.
|
|
119
|
+
* Do **after** splitting, with `Preprocessor` / `prepare_data`: filling, outliers, scaling, encoding.
|
|
120
|
+
* `quick_clean` and the single functions (`fill_missing`, `normalize`, ...) are great for exploring and
|
|
121
|
+
for small exercises, but they use the whole table.
|
|
122
|
+
|
|
123
|
+
Also drop ID columns (customer id, row number) before you prepare data. They are not useful for prediction.
|
|
124
|
+
|
|
125
|
+
## Develop and test
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
python -m venv venv
|
|
129
|
+
venv\Scripts\activate # macOS / Linux: source venv/bin/activate
|
|
130
|
+
pip install -r requirements-dev.txt
|
|
131
|
+
pip install -e .
|
|
132
|
+
pytest
|
|
133
|
+
python examples/demo.py
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Publish
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
python -m build
|
|
140
|
+
twine upload --repository testpypi dist/* # test first
|
|
141
|
+
twine upload dist/*
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Check that the name `kryzokit` is free on pypi.org first; if it is taken change `name` in
|
|
145
|
+
`pyproject.toml` (the import name `kryzokit` can stay). Raise `version` for every new upload.
|
|
146
|
+
|
|
147
|
+
## License
|
|
148
|
+
|
|
149
|
+
MIT
|
|
150
|
+
# kryzokit-project
|
kryzokit-0.1.0/README.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# kryzokit
|
|
2
|
+
|
|
3
|
+
**Data preprocessing made easy.** Clean, scale, encode and split a pandas table in a few readable lines,
|
|
4
|
+
so you can spend your time on the model instead of on boilerplate. Made for students and beginners.
|
|
5
|
+
|
|
6
|
+
```python
|
|
7
|
+
import kryzokit as kp
|
|
8
|
+
|
|
9
|
+
X_train, X_test, y_train, y_test, prep = kp.prepare_data(df, "target")
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
That one line splits your data, fills missing values, scales the numbers and one-hot encodes the text,
|
|
13
|
+
learning everything from the **training rows only** (no data leakage).
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install kryzokit # after it is published on PyPI
|
|
19
|
+
pip install -e . # from this folder, while developing
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Needs Python 3.9+, pandas, numpy and matplotlib.
|
|
23
|
+
|
|
24
|
+
## Five-minute tour
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import kryzokit as kp
|
|
28
|
+
|
|
29
|
+
df = kp.sample_data() # a messy practice table
|
|
30
|
+
print(kp.overview(df)) # type, missing, unique values, example - for every column
|
|
31
|
+
kp.plot_missing(df) # chart of missing values
|
|
32
|
+
|
|
33
|
+
# safe clean-up steps
|
|
34
|
+
df = kp.clean_column_names(df) # ' Annual Income ($)' -> 'annual_income'
|
|
35
|
+
df = kp.strip_text(df) # 'Dhaka ' -> 'Dhaka'
|
|
36
|
+
df = kp.drop_duplicates(df)
|
|
37
|
+
|
|
38
|
+
# the whole ML preparation
|
|
39
|
+
X_train, X_test, y_train, y_test, prep = kp.prepare_data(df, "purchased", stratify=True)
|
|
40
|
+
|
|
41
|
+
# new data later? use the same preparation
|
|
42
|
+
X_new = prep.transform(new_rows)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## All functions
|
|
46
|
+
|
|
47
|
+
Every function returns a **new** table and never changes the one you give it.
|
|
48
|
+
|
|
49
|
+
| Group | Function | What it does |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| Look | `overview(df)` | One row per column: type, missing, unique values, example |
|
|
52
|
+
| | `missing_report(df)` | Missing count and percent per column, worst first |
|
|
53
|
+
| | `histogram(df, "col")`, `plot_missing(df)` | Quick charts (`show=False` to get the chart without opening a window) |
|
|
54
|
+
| Clean | `clean_column_names(df)` | Lowercase names with underscores |
|
|
55
|
+
| | `strip_text(df)` | Remove spaces around text |
|
|
56
|
+
| | `drop_duplicates(df)` | Remove repeated rows |
|
|
57
|
+
| Missing | `fill_missing(df, strategy="auto")` | `auto` (numbers: median, text: most common), `mean`, `median`, `mode`, `constant` |
|
|
58
|
+
| | `drop_missing_columns(df, threshold=0.5)` | Drop columns with too many empty cells |
|
|
59
|
+
| | `drop_missing_rows(df)` | Drop rows that have empty cells |
|
|
60
|
+
| Outliers | `clip_outliers(df, method="iqr")` | Pull extreme values back to the normal range (`iqr` or `zscore`) |
|
|
61
|
+
| | `remove_outliers(df, method="iqr")` | Drop rows with extreme values |
|
|
62
|
+
| Scale | `normalize(df)` | Min-max: values from 0 to 1 |
|
|
63
|
+
| | `standardize(df)` | Z-score: mean 0, standard deviation 1 |
|
|
64
|
+
| Encode | `label_encode(df)` | Category -> number (`return_mapping=True` shows which) |
|
|
65
|
+
| | `one_hot(df)` | One 0/1 column per category |
|
|
66
|
+
| Split | `train_test_split(df, "target")` | `X_train, X_test, y_train, y_test` (`stratify=True` keeps class shares) |
|
|
67
|
+
| One call | `quick_clean(df)` | Names + text + duplicates + missing values, all at once |
|
|
68
|
+
| | `Preprocessor(...)` | Learn on train data, apply to test/new data |
|
|
69
|
+
| | `prepare_data(df, "target")` | Split + `Preprocessor` in one line |
|
|
70
|
+
| Practice | `sample_data()` | A messy table with a 0/1 `Purchased` column |
|
|
71
|
+
|
|
72
|
+
## Preprocessor options
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
prep = kp.Preprocessor(
|
|
76
|
+
fill="auto", # "auto", "mean", "median", "mode" or None
|
|
77
|
+
scale="standard", # None, "minmax" or "standard"
|
|
78
|
+
encode="onehot", # None, "onehot" or "label"
|
|
79
|
+
outliers="iqr", # None, "iqr" or "zscore" (clips extreme numbers)
|
|
80
|
+
drop_missing_above=0.5, # drop columns with more than 50 % missing
|
|
81
|
+
)
|
|
82
|
+
X_train = prep.fit_transform(X_train) # learn from the training rows
|
|
83
|
+
X_test = prep.transform(X_test) # reuse exactly the same numbers
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Give it the **features only** (no target column). Unknown categories in new data become all zeros
|
|
87
|
+
(`onehot`) or `-1` (`label`).
|
|
88
|
+
|
|
89
|
+
## Important rule: learn from the training data only
|
|
90
|
+
|
|
91
|
+
Filling, scaling and encoding use numbers calculated from the data (a median, a mean, a list of
|
|
92
|
+
categories). If you calculate them on the **whole** table before splitting, information from the test
|
|
93
|
+
rows leaks into training and your test score looks better than it really is.
|
|
94
|
+
|
|
95
|
+
* Safe before splitting (they do not look at other rows): `clean_column_names`, `strip_text`, `drop_duplicates`.
|
|
96
|
+
* Do **after** splitting, with `Preprocessor` / `prepare_data`: filling, outliers, scaling, encoding.
|
|
97
|
+
* `quick_clean` and the single functions (`fill_missing`, `normalize`, ...) are great for exploring and
|
|
98
|
+
for small exercises, but they use the whole table.
|
|
99
|
+
|
|
100
|
+
Also drop ID columns (customer id, row number) before you prepare data. They are not useful for prediction.
|
|
101
|
+
|
|
102
|
+
## Develop and test
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
python -m venv venv
|
|
106
|
+
venv\Scripts\activate # macOS / Linux: source venv/bin/activate
|
|
107
|
+
pip install -r requirements-dev.txt
|
|
108
|
+
pip install -e .
|
|
109
|
+
pytest
|
|
110
|
+
python examples/demo.py
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Publish
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
python -m build
|
|
117
|
+
twine upload --repository testpypi dist/* # test first
|
|
118
|
+
twine upload dist/*
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Check that the name `kryzokit` is free on pypi.org first; if it is taken change `name` in
|
|
122
|
+
`pyproject.toml` (the import name `kryzokit` can stay). Raise `version` for every new upload.
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT
|
|
127
|
+
# kryzokit-project
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""kryzokit - data preprocessing made easy.
|
|
2
|
+
|
|
3
|
+
import kryzokit as kp
|
|
4
|
+
|
|
5
|
+
df = kp.quick_clean(df) # one-call clean-up
|
|
6
|
+
X_train, X_test, y_train, y_test, prep = kp.prepare_data(df, "target")
|
|
7
|
+
"""
|
|
8
|
+
from .cleaning import (clean_column_names, clip_outliers, drop_duplicates, drop_missing_columns,
|
|
9
|
+
drop_missing_rows, fill_missing, remove_outliers, strip_text)
|
|
10
|
+
from .datasets import sample_data
|
|
11
|
+
from .encoding import label_encode, one_hot
|
|
12
|
+
from .pipeline import Preprocessor, prepare_data, quick_clean
|
|
13
|
+
from .plot import histogram, plot_missing
|
|
14
|
+
from .report import missing_report, overview
|
|
15
|
+
from .split import train_test_split
|
|
16
|
+
from .transform import normalize, standardize
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
__all__ = [
|
|
20
|
+
"clean_column_names", "strip_text", "drop_duplicates", "fill_missing", "drop_missing_columns",
|
|
21
|
+
"drop_missing_rows", "clip_outliers", "remove_outliers", "normalize", "standardize",
|
|
22
|
+
"label_encode", "one_hot", "train_test_split", "missing_report", "overview",
|
|
23
|
+
"histogram", "plot_missing", "quick_clean", "Preprocessor", "prepare_data", "sample_data",
|
|
24
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Small helpers shared by the other modules (not part of the public API)."""
|
|
2
|
+
from pandas.api.types import is_bool_dtype, is_datetime64_any_dtype, is_numeric_dtype
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def numeric_columns(df):
|
|
6
|
+
"""Names of numeric columns (booleans are not counted as numbers)."""
|
|
7
|
+
return [c for c in df.columns if is_numeric_dtype(df[c]) and not is_bool_dtype(df[c])]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def category_columns(df):
|
|
11
|
+
"""Names of text / category columns (not numbers, booleans or dates)."""
|
|
12
|
+
return [
|
|
13
|
+
c for c in df.columns
|
|
14
|
+
if not is_numeric_dtype(df[c]) and not is_bool_dtype(df[c]) and not is_datetime64_any_dtype(df[c])
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def pick_columns(df, columns, default):
|
|
19
|
+
"""Return a list of column names, checking that they exist.
|
|
20
|
+
|
|
21
|
+
columns=None -> use `default`
|
|
22
|
+
columns="a" -> ["a"]
|
|
23
|
+
"""
|
|
24
|
+
if columns is None:
|
|
25
|
+
return list(default)
|
|
26
|
+
if isinstance(columns, str):
|
|
27
|
+
columns = [columns]
|
|
28
|
+
missing = [c for c in columns if c not in df.columns]
|
|
29
|
+
if missing:
|
|
30
|
+
raise KeyError(f"Column(s) not found: {missing}. Available columns: {list(df.columns)}")
|
|
31
|
+
return list(columns)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def require_numeric(df, columns, action):
|
|
35
|
+
"""Raise a friendly error if any of `columns` is not numeric."""
|
|
36
|
+
numeric = set(numeric_columns(df))
|
|
37
|
+
bad = [c for c in columns if c not in numeric]
|
|
38
|
+
if bad:
|
|
39
|
+
raise ValueError(f"{action} only works on numeric columns, but these are not numeric: {bad}")
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Cleaning: names, text, duplicates, missing values and outliers."""
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from ._utils import category_columns, numeric_columns, pick_columns, require_numeric
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clean_column_names(df):
|
|
10
|
+
"""Make column names lowercase with underscores: ' Annual Income ($)' -> 'annual_income'."""
|
|
11
|
+
df = df.copy()
|
|
12
|
+
used, new = set(), []
|
|
13
|
+
for name in df.columns:
|
|
14
|
+
base = re.sub(r"[^0-9a-zA-Z]+", "_", str(name).strip().lower()).strip("_") or "column"
|
|
15
|
+
candidate, k = base, 2
|
|
16
|
+
while candidate in used:
|
|
17
|
+
candidate = f"{base}_{k}"
|
|
18
|
+
k += 1
|
|
19
|
+
used.add(candidate)
|
|
20
|
+
new.append(candidate)
|
|
21
|
+
df.columns = new
|
|
22
|
+
return df
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def strip_text(df, columns=None):
|
|
26
|
+
"""Remove spaces at the start and end of text values ('Dhaka ' -> 'Dhaka')."""
|
|
27
|
+
df = df.copy()
|
|
28
|
+
for c in pick_columns(df, columns, category_columns(df)):
|
|
29
|
+
df[c] = df[c].astype(object).map(lambda v: v.strip() if isinstance(v, str) else v)
|
|
30
|
+
return df
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def drop_duplicates(df, subset=None):
|
|
34
|
+
"""Remove repeated rows (keeps the first one) and renumber the rows."""
|
|
35
|
+
subset = pick_columns(df, subset, df.columns) if subset is not None else None
|
|
36
|
+
return df.drop_duplicates(subset=subset).reset_index(drop=True)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ----------------------------------------------------------------- missing values
|
|
40
|
+
_STRATEGIES = ("auto", "mean", "median", "mode", "constant")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _fill_value(series, strategy, value, is_numeric):
|
|
44
|
+
"""The single value that should replace the missing cells of one column."""
|
|
45
|
+
if strategy == "constant":
|
|
46
|
+
return value
|
|
47
|
+
if strategy == "auto":
|
|
48
|
+
strategy = "median" if is_numeric else "mode"
|
|
49
|
+
if strategy in ("mean", "median"):
|
|
50
|
+
result = series.mean() if strategy == "mean" else series.median()
|
|
51
|
+
else:
|
|
52
|
+
modes = series.mode()
|
|
53
|
+
result = modes.iloc[0] if len(modes) else None
|
|
54
|
+
return None if result is None or pd.isna(result) else result
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def fill_missing(df, strategy="auto", columns=None, value=None):
|
|
58
|
+
"""Fill empty cells.
|
|
59
|
+
|
|
60
|
+
strategy="auto" numbers -> median, text -> most common value (default)
|
|
61
|
+
strategy="mean" column average (numeric columns only)
|
|
62
|
+
strategy="median" column middle value (numeric columns only)
|
|
63
|
+
strategy="mode" most common value
|
|
64
|
+
strategy="constant" the `value` you give, e.g. fill_missing(df, "constant", value=0)
|
|
65
|
+
|
|
66
|
+
columns=None means "all suitable columns".
|
|
67
|
+
"""
|
|
68
|
+
if strategy not in _STRATEGIES:
|
|
69
|
+
raise ValueError(f"strategy must be one of {_STRATEGIES}, not {strategy!r}")
|
|
70
|
+
if strategy == "constant" and value is None:
|
|
71
|
+
raise ValueError("strategy='constant' needs a value, e.g. fill_missing(df, 'constant', value=0)")
|
|
72
|
+
df = df.copy()
|
|
73
|
+
numeric = numeric_columns(df)
|
|
74
|
+
if columns is None:
|
|
75
|
+
cols = numeric if strategy in ("mean", "median") else list(df.columns)
|
|
76
|
+
else:
|
|
77
|
+
cols = pick_columns(df, columns, [])
|
|
78
|
+
if strategy in ("mean", "median"):
|
|
79
|
+
require_numeric(df, cols, f"strategy='{strategy}'")
|
|
80
|
+
for c in cols:
|
|
81
|
+
fill = _fill_value(df[c], strategy, value, c in numeric)
|
|
82
|
+
if fill is not None:
|
|
83
|
+
df[c] = df[c].fillna(fill)
|
|
84
|
+
return df
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def drop_missing_columns(df, threshold=0.5):
|
|
88
|
+
"""Drop columns where MORE than `threshold` (0 to 1) of the values are missing."""
|
|
89
|
+
if not 0 <= threshold <= 1:
|
|
90
|
+
raise ValueError("threshold must be between 0 and 1")
|
|
91
|
+
if len(df) == 0:
|
|
92
|
+
return df.copy()
|
|
93
|
+
fraction = df.isna().mean()
|
|
94
|
+
return df.drop(columns=[c for c in df.columns if fraction[c] > threshold])
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def drop_missing_rows(df, columns=None):
|
|
98
|
+
"""Drop rows that have a missing value (in `columns`, or in any column)."""
|
|
99
|
+
columns = pick_columns(df, columns, []) if columns is not None else None
|
|
100
|
+
return df.dropna(subset=columns).reset_index(drop=True)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ----------------------------------------------------------------------- outliers
|
|
104
|
+
def _bounds(series, method, factor):
|
|
105
|
+
"""Lowest and highest value that still counts as 'normal'."""
|
|
106
|
+
s = series.dropna()
|
|
107
|
+
if method == "iqr":
|
|
108
|
+
f = 1.5 if factor is None else factor
|
|
109
|
+
q1, q3 = s.quantile(0.25), s.quantile(0.75)
|
|
110
|
+
spread = q3 - q1
|
|
111
|
+
return q1 - f * spread, q3 + f * spread
|
|
112
|
+
if method == "zscore":
|
|
113
|
+
f = 3 if factor is None else factor
|
|
114
|
+
mean, std = s.mean(), s.std(ddof=0)
|
|
115
|
+
return mean - f * std, mean + f * std
|
|
116
|
+
raise ValueError("method must be 'iqr' or 'zscore'")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def clip_outliers(df, columns=None, method="iqr", factor=None):
|
|
120
|
+
"""Pull extreme values back to the nearest normal value (rows are kept).
|
|
121
|
+
|
|
122
|
+
method="iqr" normal = Q1 - 1.5*IQR ... Q3 + 1.5*IQR (default factor 1.5)
|
|
123
|
+
method="zscore" normal = mean +- 3 standard deviations (default factor 3)
|
|
124
|
+
"""
|
|
125
|
+
df = df.copy()
|
|
126
|
+
cols = pick_columns(df, columns, numeric_columns(df))
|
|
127
|
+
require_numeric(df, cols, "clip_outliers")
|
|
128
|
+
for c in cols:
|
|
129
|
+
low, high = _bounds(df[c], method, factor)
|
|
130
|
+
if not (pd.isna(low) or pd.isna(high)):
|
|
131
|
+
df[c] = df[c].clip(low, high)
|
|
132
|
+
return df
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def remove_outliers(df, columns=None, method="iqr", factor=None):
|
|
136
|
+
"""Drop the rows that contain an extreme value (see clip_outliers for the rules)."""
|
|
137
|
+
cols = pick_columns(df, columns, numeric_columns(df))
|
|
138
|
+
require_numeric(df, cols, "remove_outliers")
|
|
139
|
+
keep = pd.Series(True, index=df.index)
|
|
140
|
+
for c in cols:
|
|
141
|
+
low, high = _bounds(df[c], method, factor)
|
|
142
|
+
if not (pd.isna(low) or pd.isna(high)):
|
|
143
|
+
keep &= df[c].isna() | ((df[c] >= low) & (df[c] <= high))
|
|
144
|
+
return df[keep].reset_index(drop=True)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""A small messy practice dataset."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def sample_data(n=200, seed=0):
|
|
7
|
+
"""Make a messy customer table for practice.
|
|
8
|
+
|
|
9
|
+
It contains: ugly column names, spaces around text, missing values,
|
|
10
|
+
a few extreme incomes and 5 repeated rows. The column 'Purchased' (0/1)
|
|
11
|
+
is the thing you would try to predict.
|
|
12
|
+
"""
|
|
13
|
+
rng = np.random.default_rng(seed)
|
|
14
|
+
age = rng.integers(18, 70, n).astype(float)
|
|
15
|
+
income = rng.normal(50000, 15000, n).round(0)
|
|
16
|
+
satisfaction = rng.integers(1, 6, n).astype(float)
|
|
17
|
+
city = rng.choice(["Dhaka", "Chattogram", "Sylhet", "Khulna"], n).astype(object)
|
|
18
|
+
gender = rng.choice(["Male", "Female"], n).astype(object)
|
|
19
|
+
chance = 1 / (1 + np.exp(-((income - 50000) / 15000 + (satisfaction - 3) / 2)))
|
|
20
|
+
purchased = (rng.random(n) < chance).astype(int)
|
|
21
|
+
|
|
22
|
+
# make it messy
|
|
23
|
+
city = np.where(rng.random(n) < 0.15, [str(c) + " " for c in city], city).astype(object)
|
|
24
|
+
income[rng.choice(n, 3, replace=False)] *= 10 # extreme values
|
|
25
|
+
age[rng.random(n) < 0.08] = np.nan
|
|
26
|
+
income[rng.random(n) < 0.05] = np.nan
|
|
27
|
+
satisfaction[rng.random(n) < 0.06] = np.nan
|
|
28
|
+
city[rng.random(n) < 0.05] = None
|
|
29
|
+
|
|
30
|
+
df = pd.DataFrame({
|
|
31
|
+
"Customer ID": np.arange(1, n + 1),
|
|
32
|
+
" Age ": age,
|
|
33
|
+
"Annual Income ($)": income,
|
|
34
|
+
"City": city,
|
|
35
|
+
"Gender": gender,
|
|
36
|
+
"Satisfaction": satisfaction,
|
|
37
|
+
"Purchased": purchased,
|
|
38
|
+
})
|
|
39
|
+
return pd.concat([df, df.iloc[:5]], ignore_index=True) # 5 repeated rows
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Turning text categories into numbers."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
from ._utils import category_columns, pick_columns
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def label_encode(df, columns=None, return_mapping=False):
|
|
8
|
+
"""Replace each category by a whole number: 'Dhaka'->0, 'Khulna'->1 ... (alphabetical).
|
|
9
|
+
|
|
10
|
+
Missing values stay missing. With return_mapping=True you also get the
|
|
11
|
+
dictionaries that show which number belongs to which category.
|
|
12
|
+
"""
|
|
13
|
+
df = df.copy()
|
|
14
|
+
mappings = {}
|
|
15
|
+
for c in pick_columns(df, columns, category_columns(df)):
|
|
16
|
+
values = df[c].astype(object)
|
|
17
|
+
categories = sorted(values.dropna().unique(), key=str)
|
|
18
|
+
mapping = {value: number for number, value in enumerate(categories)}
|
|
19
|
+
df[c] = values.map(mapping)
|
|
20
|
+
mappings[c] = mapping
|
|
21
|
+
return (df, mappings) if return_mapping else df
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def one_hot(df, columns=None, drop_first=False):
|
|
25
|
+
"""One new 0/1 column per category: city -> city_Dhaka, city_Khulna ..."""
|
|
26
|
+
cols = pick_columns(df, columns, category_columns(df))
|
|
27
|
+
if not cols:
|
|
28
|
+
return df.copy()
|
|
29
|
+
return pd.get_dummies(df, columns=cols, drop_first=drop_first, dtype=int)
|