kryzokit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kryzokit/__init__.py ADDED
@@ -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
+ ]
kryzokit/_utils.py ADDED
@@ -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}")
kryzokit/cleaning.py ADDED
@@ -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)
kryzokit/datasets.py ADDED
@@ -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
kryzokit/encoding.py ADDED
@@ -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)
kryzokit/pipeline.py ADDED
@@ -0,0 +1,209 @@
1
+ """One-call helpers: quick_clean, Preprocessor and prepare_data."""
2
+ import pandas as pd
3
+
4
+ from ._utils import category_columns, numeric_columns
5
+ from .cleaning import _bounds, _fill_value, clean_column_names, drop_duplicates, fill_missing, strip_text
6
+ from .split import train_test_split
7
+
8
+
9
+ def quick_clean(df):
10
+ """The everyday clean-up in ONE call.
11
+
12
+ 1. tidy column names 2. strip spaces in text 3. drop repeated rows
13
+ 4. fill missing values (numbers -> median, text -> most common)
14
+ """
15
+ df = clean_column_names(df)
16
+ df = strip_text(df)
17
+ df = drop_duplicates(df)
18
+ return fill_missing(df)
19
+
20
+
21
+ def _check(value, allowed, name):
22
+ if value not in allowed:
23
+ raise ValueError(f"{name} must be one of {allowed}, not {value!r}")
24
+
25
+
26
+ class Preprocessor:
27
+ """Learn the preprocessing from TRAINING data, then apply it to any data.
28
+
29
+ This is how you avoid "data leakage": the median, the scaling numbers and the
30
+ list of categories come from the training rows only, and the very same values
31
+ are then used for the test rows (or for new data later).
32
+
33
+ prep = Preprocessor(scale="standard", encode="onehot")
34
+ X_train_ready = prep.fit_transform(X_train)
35
+ X_test_ready = prep.transform(X_test)
36
+
37
+ Settings (all optional)
38
+ -----------------------
39
+ clean_names tidy the column names (True)
40
+ strip_text remove spaces around text values (True)
41
+ drop_missing_above drop columns with a larger missing share (None, or e.g. 0.5)
42
+ fill "auto", "mean", "median", "mode" or None ("auto")
43
+ outliers None, "iqr" or "zscore": clip extreme numbers
44
+ outlier_factor override the default 1.5 (iqr) / 3 (zscore)
45
+ scale None, "minmax" or "standard"
46
+ encode None, "onehot" or "label"
47
+ drop_first with onehot, drop one column per category (False)
48
+
49
+ Pass only the FEATURES (without the target column). Extra columns that were not
50
+ there during fit() are ignored by transform().
51
+ """
52
+
53
+ def __init__(self, clean_names=True, strip_text=True, drop_missing_above=None, fill="auto",
54
+ outliers=None, outlier_factor=None, scale=None, encode=None, drop_first=False):
55
+ _check(fill, (None, "auto", "mean", "median", "mode"), "fill")
56
+ _check(outliers, (None, "iqr", "zscore"), "outliers")
57
+ _check(scale, (None, "minmax", "standard"), "scale")
58
+ _check(encode, (None, "onehot", "label"), "encode")
59
+ if drop_missing_above is not None and not 0 <= drop_missing_above <= 1:
60
+ raise ValueError("drop_missing_above must be between 0 and 1")
61
+ self.clean_names = clean_names
62
+ self.strip_text = strip_text
63
+ self.drop_missing_above = drop_missing_above
64
+ self.fill = fill
65
+ self.outliers = outliers
66
+ self.outlier_factor = outlier_factor
67
+ self.scale = scale
68
+ self.encode = encode
69
+ self.drop_first = drop_first
70
+
71
+ def __repr__(self):
72
+ settings = ", ".join(f"{k}={v!r}" for k, v in vars(self).items() if not k.endswith("_"))
73
+ return f"Preprocessor({settings})"
74
+
75
+ # ------------------------------------------------------------------ steps
76
+ def _prepare(self, df):
77
+ X = clean_column_names(df) if self.clean_names else df.copy()
78
+ if X.columns.duplicated().any():
79
+ raise ValueError("Column names must be unique (try clean_names=True)")
80
+ for c in X.columns:
81
+ if isinstance(X[c].dtype, pd.CategoricalDtype):
82
+ X[c] = X[c].astype(object)
83
+ return strip_text(X) if self.strip_text else X
84
+
85
+ def _fill(self, X):
86
+ for c, value in self.fill_values_.items():
87
+ X[c] = X[c].fillna(value)
88
+ return X
89
+
90
+ def _clip(self, X):
91
+ for c, (low, high) in self.bounds_.items():
92
+ X[c] = X[c].clip(low, high)
93
+ return X
94
+
95
+ def _scale(self, X):
96
+ for c, (center, spread) in self.scale_params_.items():
97
+ X[c] = (X[c] - center) / spread
98
+ return X
99
+
100
+ def _encode(self, X):
101
+ if not self.encode:
102
+ return X
103
+ parts = []
104
+ for c in X.columns:
105
+ if c not in self.categories_:
106
+ parts.append(X[c])
107
+ continue
108
+ categories = self.categories_[c]
109
+ if self.encode == "label":
110
+ numbers = {value: i for i, value in enumerate(categories)}
111
+ parts.append(X[c].map(numbers).fillna(-1).astype(int)) # unknown or missing -> -1
112
+ else:
113
+ use = categories[1:] if self.drop_first else categories
114
+ parts.extend((X[c] == value).astype(int).rename(f"{c}_{value}") for value in use)
115
+ return pd.concat(parts, axis=1) if parts else X
116
+
117
+ # -------------------------------------------------------------------- API
118
+ def fit(self, df):
119
+ """Learn everything from `df` (use your TRAINING data)."""
120
+ X = self._prepare(df)
121
+ self.input_columns_ = list(X.columns)
122
+
123
+ if self.drop_missing_above is None:
124
+ self.dropped_columns_ = []
125
+ else:
126
+ share = X.isna().mean()
127
+ self.dropped_columns_ = [c for c in X.columns if share[c] > self.drop_missing_above]
128
+ X = X.drop(columns=self.dropped_columns_)
129
+ self.numeric_columns_ = numeric_columns(X)
130
+ self.category_columns_ = category_columns(X)
131
+
132
+ self.fill_values_ = {}
133
+ if self.fill is not None:
134
+ for c in X.columns:
135
+ is_num = c in self.numeric_columns_
136
+ if self.fill == "auto":
137
+ strategy = "median" if is_num else "mode"
138
+ elif self.fill in ("mean", "median") and not is_num:
139
+ strategy = "mode"
140
+ else:
141
+ strategy = self.fill
142
+ value = _fill_value(X[c], strategy, None, is_num)
143
+ if value is not None:
144
+ self.fill_values_[c] = value
145
+ X = self._fill(X)
146
+
147
+ self.bounds_ = {}
148
+ if self.outliers:
149
+ for c in self.numeric_columns_:
150
+ low, high = _bounds(X[c], self.outliers, self.outlier_factor)
151
+ if not (pd.isna(low) or pd.isna(high)):
152
+ self.bounds_[c] = (low, high)
153
+ X = self._clip(X)
154
+
155
+ self.scale_params_ = {}
156
+ if self.scale:
157
+ for c in self.numeric_columns_:
158
+ if self.scale == "minmax":
159
+ center = X[c].min()
160
+ spread = X[c].max() - center
161
+ else:
162
+ center, spread = X[c].mean(), X[c].std(ddof=0)
163
+ if pd.isna(spread) or spread == 0:
164
+ spread = 1.0
165
+ if pd.isna(center):
166
+ center = 0.0
167
+ self.scale_params_[c] = (center, spread)
168
+ X = self._scale(X)
169
+
170
+ self.categories_ = {}
171
+ if self.encode:
172
+ for c in self.category_columns_:
173
+ self.categories_[c] = sorted(X[c].dropna().unique(), key=str)
174
+ self.feature_names_ = list(self._encode(X).columns)
175
+ return self
176
+
177
+ def transform(self, df):
178
+ """Apply what fit() learned. Works on test data or brand-new data."""
179
+ if not hasattr(self, "input_columns_"):
180
+ raise RuntimeError("Call fit() (or fit_transform) first, with your training data")
181
+ X = self._prepare(df)
182
+ missing = [c for c in self.input_columns_ if c not in X.columns]
183
+ if missing:
184
+ raise KeyError(f"These columns were present in fit() but are missing now: {missing}")
185
+ X = X[self.input_columns_].drop(columns=self.dropped_columns_)
186
+ return self._encode(self._scale(self._clip(self._fill(X))))
187
+
188
+ def fit_transform(self, df):
189
+ """fit() and transform() on the same data (for the training set)."""
190
+ return self.fit(df).transform(df)
191
+
192
+
193
+ def prepare_data(df, target, test_size=0.2, seed=42, stratify=False, **options):
194
+ """Split, fit on train, transform both: the whole ML preparation in ONE line.
195
+
196
+ X_train, X_test, y_train, y_test, prep = prepare_data(df, "Purchased")
197
+
198
+ Rows without a target value are dropped first. `options` are the Preprocessor
199
+ settings; by default numbers are standardized and text is one-hot encoded.
200
+ The last returned item is the fitted Preprocessor: keep it to prepare new data later.
201
+ """
202
+ if target not in df.columns:
203
+ raise KeyError(f"Target column {target!r} not found. Available columns: {list(df.columns)}")
204
+ df = df.dropna(subset=[target])
205
+ X_train, X_test, y_train, y_test = train_test_split(df, target, test_size, seed, stratify)
206
+ settings = {"scale": "standard", "encode": "onehot"}
207
+ settings.update(options)
208
+ prep = Preprocessor(**settings)
209
+ return prep.fit_transform(X_train), prep.transform(X_test), y_train, y_test, prep
kryzokit/plot.py ADDED
@@ -0,0 +1,26 @@
1
+ """Quick charts."""
2
+ import matplotlib.pyplot as plt
3
+
4
+ from ._utils import pick_columns
5
+ from .report import missing_report
6
+
7
+
8
+ def histogram(df, column, bins=10, show=True):
9
+ """Bar chart of how often each range of values appears in one column."""
10
+ pick_columns(df, column, [])
11
+ ax = df[column].plot(kind="hist", bins=bins, edgecolor="black")
12
+ ax.set_title(column)
13
+ if show:
14
+ plt.show()
15
+ return ax
16
+
17
+
18
+ def plot_missing(df, show=True):
19
+ """Bar chart of the percentage of missing values in each column."""
20
+ ax = missing_report(df)["percent"].plot(kind="bar", edgecolor="black")
21
+ ax.set_ylabel("% missing")
22
+ ax.set_title("Missing values per column")
23
+ plt.tight_layout()
24
+ if show:
25
+ plt.show()
26
+ return ax
kryzokit/report.py ADDED
@@ -0,0 +1,26 @@
1
+ """Quick reports about a table."""
2
+ import pandas as pd
3
+
4
+
5
+ def missing_report(df):
6
+ """How many values are missing in each column (most missing first)."""
7
+ missing = df.isna().sum()
8
+ percent = (missing / len(df) * 100).round(2) if len(df) else missing * 0.0
9
+ report = pd.DataFrame({"missing": missing, "percent": percent})
10
+ return report.sort_values("missing", ascending=False, kind="stable")
11
+
12
+
13
+ def overview(df):
14
+ """One row per column: type, missing, unique values and an example value."""
15
+ rows = {}
16
+ for c in df.columns:
17
+ s = df[c]
18
+ present = s.dropna()
19
+ rows[c] = {
20
+ "dtype": str(s.dtype),
21
+ "missing": int(s.isna().sum()),
22
+ "percent": round(float(s.isna().mean()) * 100, 2) if len(s) else 0.0,
23
+ "unique": int(s.nunique()),
24
+ "example": present.iloc[0] if len(present) else None,
25
+ }
26
+ return pd.DataFrame.from_dict(rows, orient="index")
kryzokit/split.py ADDED
@@ -0,0 +1,46 @@
1
+ """Splitting data into training and test parts."""
2
+ import numpy as np
3
+ import pandas as pd
4
+
5
+
6
+ def train_test_split(df, target, test_size=0.2, seed=42, stratify=False):
7
+ """Split a table into X_train, X_test, y_train, y_test.
8
+
9
+ target name of the column you want to predict
10
+ test_size fraction used for testing (0.2 = 20 %)
11
+ seed same seed -> same split every time
12
+ stratify True keeps the share of every class equal in both parts
13
+ """
14
+ if target not in df.columns:
15
+ raise KeyError(f"Target column {target!r} not found. Available columns: {list(df.columns)}")
16
+ if not 0 < test_size < 1:
17
+ raise ValueError("test_size must be between 0 and 1, for example 0.2")
18
+ n = len(df)
19
+ if n < 2:
20
+ raise ValueError("Need at least 2 rows to split the data")
21
+ rng = np.random.default_rng(seed)
22
+
23
+ if stratify:
24
+ codes = pd.factorize(df[target])[0]
25
+ test_positions = []
26
+ for code in np.unique(codes):
27
+ group = rng.permutation(np.flatnonzero(codes == code))
28
+ k = int(round(len(group) * test_size))
29
+ if len(group) > 1:
30
+ k = min(max(k, 1), len(group) - 1)
31
+ test_positions.extend(group[:k])
32
+ test_positions = np.array(sorted(test_positions), dtype=int)
33
+ else:
34
+ k = min(max(int(round(n * test_size)), 1), n - 1)
35
+ test_positions = np.sort(rng.permutation(n)[:k])
36
+
37
+ is_test = np.zeros(n, dtype=bool)
38
+ is_test[test_positions] = True
39
+ X = df.drop(columns=target)
40
+ y = df[target]
41
+ return (
42
+ X[~is_test].reset_index(drop=True),
43
+ X[is_test].reset_index(drop=True),
44
+ y[~is_test].reset_index(drop=True),
45
+ y[is_test].reset_index(drop=True),
46
+ )
kryzokit/transform.py ADDED
@@ -0,0 +1,29 @@
1
+ """Scaling numeric columns."""
2
+ from ._utils import numeric_columns, pick_columns, require_numeric
3
+
4
+
5
+ def normalize(df, columns=None):
6
+ """Min-max scaling: every value becomes a number from 0 to 1."""
7
+ df = df.copy()
8
+ cols = pick_columns(df, columns, numeric_columns(df))
9
+ require_numeric(df, cols, "normalize")
10
+ for c in cols:
11
+ low = df[c].min()
12
+ span = df[c].max() - low
13
+ if span != span or span == 0: # NaN (empty column) or constant column
14
+ span = 1
15
+ df[c] = (df[c] - low) / span
16
+ return df
17
+
18
+
19
+ def standardize(df, columns=None):
20
+ """Z-score scaling: mean becomes 0 and standard deviation becomes 1."""
21
+ df = df.copy()
22
+ cols = pick_columns(df, columns, numeric_columns(df))
23
+ require_numeric(df, cols, "standardize")
24
+ for c in cols:
25
+ std = df[c].std(ddof=0)
26
+ if std != std or std == 0:
27
+ std = 1
28
+ df[c] = (df[c] - df[c].mean()) / std
29
+ return df
@@ -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
@@ -0,0 +1,15 @@
1
+ kryzokit/__init__.py,sha256=Bi4Y-iKullj_exLoIVGc_gTGuXNUlxaJKKP-IpVJgZ8,1124
2
+ kryzokit/_utils.py,sha256=I74E6RddBKJov1LK63jCJY7eSbHH7lQBAG129mJ7yys,1421
3
+ kryzokit/cleaning.py,sha256=95d5cKL9C-P7sIWTLrGDVUYCCbJli7OeYwNyxv-sJu8,5623
4
+ kryzokit/datasets.py,sha256=FjRkT_IPWeHmIb9JNovyDsHr8Gnr9glGLM8o6iuQGrk,1515
5
+ kryzokit/encoding.py,sha256=Vzwix64LGXyFY4CkDyas7bNqTbk6-jsFYhBoFw71Rms,1123
6
+ kryzokit/pipeline.py,sha256=_ISaDjBZzXHkb4LldrW_AXkODHUAOQyDUcmdKf5gbfY,8890
7
+ kryzokit/plot.py,sha256=pyi2hZ_JDe5VYwvkaGWTGGqL9iOR392axO_rWCxR6RY,747
8
+ kryzokit/report.py,sha256=dEdCRwQHMZBNA0I6Rqxki2bmo5ZwfWHYjDjBOfTTVW4,946
9
+ kryzokit/split.py,sha256=J2Ppi_ZM-9ej3k0DliyTRZ3ykaE5ThR4_1eYeYvxzyc,1723
10
+ kryzokit/transform.py,sha256=Yk21r7LDp6dstpVUFhc-MMl_lW6eg1K9JQwC6SWCwtM,951
11
+ kryzokit-0.1.0.dist-info/licenses/LICENSE,sha256=NXMmyEy0wLpTHPIiAroYuPLaOr4tQ4Sdnc6P_gyIZa0,1066
12
+ kryzokit-0.1.0.dist-info/METADATA,sha256=4bl5wcNX5toeHQ0soML07r0_VUE88FGaEEhFYWUhAjI,6010
13
+ kryzokit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ kryzokit-0.1.0.dist-info/top_level.txt,sha256=yQXNiMe3KAb_elP-q6O8QsT5khS614_Or6PNoIk-y3k,9
15
+ kryzokit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ kryzokit