gators 1.0.4__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.
- gators/__init__.py +1 -0
- gators/clippers/__init__.py +9 -0
- gators/clippers/custom_clipper.py +232 -0
- gators/clippers/gaussian_clipper.py +222 -0
- gators/clippers/iqr_clipper.py +175 -0
- gators/clippers/mad_clipper.py +175 -0
- gators/clippers/quantile_clipper.py +195 -0
- gators/data_cleaning/__init__.py +29 -0
- gators/data_cleaning/cast_columns.py +188 -0
- gators/data_cleaning/correlation_filter.py +183 -0
- gators/data_cleaning/drop_columns.py +82 -0
- gators/data_cleaning/drop_constant_columns.py +187 -0
- gators/data_cleaning/drop_duplicate_columns.py +237 -0
- gators/data_cleaning/drop_duplicate_rows.py +173 -0
- gators/data_cleaning/drop_high_nan_ratio.py +142 -0
- gators/data_cleaning/drop_low_cardinality.py +146 -0
- gators/data_cleaning/high_cardinality_filter.py +191 -0
- gators/data_cleaning/outlier_filter.py +372 -0
- gators/data_cleaning/rename_columns.py +79 -0
- gators/data_cleaning/replace.py +157 -0
- gators/data_cleaning/util.py +67 -0
- gators/data_cleaning/variance_filter.py +120 -0
- gators/discretizers/__init__.py +17 -0
- gators/discretizers/_base_discretizer.py +185 -0
- gators/discretizers/custom_discretizer.py +142 -0
- gators/discretizers/equal_length_discretizer.py +175 -0
- gators/discretizers/equal_size_discretizer.py +171 -0
- gators/discretizers/geometric_discretizer.py +209 -0
- gators/discretizers/kmeans_discretizer.py +175 -0
- gators/discretizers/quantile_discretizer.py +193 -0
- gators/discretizers/tree_based_discretizer.py +197 -0
- gators/encoders/__init__.py +21 -0
- gators/encoders/_base_encoder.py +103 -0
- gators/encoders/binary_encoder.py +189 -0
- gators/encoders/catboost_encoder.py +195 -0
- gators/encoders/count_encoder.py +145 -0
- gators/encoders/leave_one_out_encoder.py +231 -0
- gators/encoders/onehot_encoder.py +169 -0
- gators/encoders/ordinal_encoder.py +124 -0
- gators/encoders/rare_category_encoder.py +165 -0
- gators/encoders/target_encoder.py +141 -0
- gators/encoders/util.py +33 -0
- gators/encoders/woe_encoder.py +185 -0
- gators/feature_generation/__init__.py +32 -0
- gators/feature_generation/comparison_features.py +242 -0
- gators/feature_generation/condition_features.py +492 -0
- gators/feature_generation/distance_features.py +272 -0
- gators/feature_generation/group_lag_features.py +240 -0
- gators/feature_generation/group_scaling_features.py +268 -0
- gators/feature_generation/group_statistics_features.py +208 -0
- gators/feature_generation/is_null.py +85 -0
- gators/feature_generation/math_features.py +169 -0
- gators/feature_generation/plan_rotation_features.py +125 -0
- gators/feature_generation/polynomial_features.py +127 -0
- gators/feature_generation/ratio_features.py +217 -0
- gators/feature_generation/row_statistics_features.py +287 -0
- gators/feature_generation/rule_features.py +384 -0
- gators/feature_generation/scalar_math_features.py +350 -0
- gators/feature_generation_dt/__init__.py +20 -0
- gators/feature_generation_dt/business_time_features.py +227 -0
- gators/feature_generation_dt/cyclic_features.py +221 -0
- gators/feature_generation_dt/diff_features.py +201 -0
- gators/feature_generation_dt/duration_to_datetime.py +232 -0
- gators/feature_generation_dt/holiday_features.py +243 -0
- gators/feature_generation_dt/ordinal_features.py +161 -0
- gators/feature_generation_dt/time_bin_features.py +239 -0
- gators/feature_generation_dt/time_window_features.py +421 -0
- gators/feature_generation_str/__init__.py +33 -0
- gators/feature_generation_str/character_statistics.py +221 -0
- gators/feature_generation_str/combine_features.py +206 -0
- gators/feature_generation_str/contains.py +80 -0
- gators/feature_generation_str/endswith.py +80 -0
- gators/feature_generation_str/extract_substring.py +57 -0
- gators/feature_generation_str/interaction_features.py +137 -0
- gators/feature_generation_str/length.py +110 -0
- gators/feature_generation_str/lower.py +107 -0
- gators/feature_generation_str/ngram.py +279 -0
- gators/feature_generation_str/occurrences.py +207 -0
- gators/feature_generation_str/pattern_detector.py +224 -0
- gators/feature_generation_str/split.py +126 -0
- gators/feature_generation_str/split_extract.py +118 -0
- gators/feature_generation_str/startswith.py +80 -0
- gators/feature_generation_str/upper.py +142 -0
- gators/feature_selection/__init__.py +7 -0
- gators/feature_selection/feature_stability_index.py +68 -0
- gators/feature_selection/information_value.py +62 -0
- gators/imputers/__init__.py +11 -0
- gators/imputers/boolean_imputer.py +161 -0
- gators/imputers/groupby_imputer.py +194 -0
- gators/imputers/numeric_imputer.py +235 -0
- gators/imputers/string_imputer.py +136 -0
- gators/pipeline/README.md +157 -0
- gators/pipeline/__init__.py +3 -0
- gators/pipeline/pipeline.py +329 -0
- gators/scalers/__init__.py +19 -0
- gators/scalers/arcsin_squareroot_scaler.py +123 -0
- gators/scalers/arcsinh_scaler.py +130 -0
- gators/scalers/box_cox.py +113 -0
- gators/scalers/log_scaler.py +181 -0
- gators/scalers/minmax_scaler.py +112 -0
- gators/scalers/power_scaler.py +130 -0
- gators/scalers/standard_scaler.py +111 -0
- gators/scalers/yeo_jonhson.py +126 -0
- gators-1.0.4.dist-info/METADATA +266 -0
- gators-1.0.4.dist-info/RECORD +107 -0
- gators-1.0.4.dist-info/WHEEL +4 -0
- gators-1.0.4.dist-info/licenses/LICENSE +201 -0
gators/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.4"
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Clipping transformers for outlier handling."""
|
|
2
|
+
|
|
3
|
+
from gators.clippers.custom_clipper import CustomClipper
|
|
4
|
+
from gators.clippers.gaussian_clipper import GaussianClipper
|
|
5
|
+
from gators.clippers.iqr_clipper import IQRClipper
|
|
6
|
+
from gators.clippers.mad_clipper import MADClipper
|
|
7
|
+
from gators.clippers.quantile_clipper import QuantileClipper
|
|
8
|
+
|
|
9
|
+
__all__ = ["CustomClipper", "GaussianClipper", "IQRClipper", "MADClipper", "QuantileClipper"]
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Custom clipper for capping values with user-defined bounds."""
|
|
2
|
+
|
|
3
|
+
from typing import Dict, Optional
|
|
4
|
+
|
|
5
|
+
import polars as pl
|
|
6
|
+
import polars.selectors as cs
|
|
7
|
+
from pydantic import BaseModel, Field, PrivateAttr, field_validator
|
|
8
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CustomClipper(BaseModel, BaseEstimator, TransformerMixin):
|
|
12
|
+
"""Clip column values using custom lower and upper bounds.
|
|
13
|
+
|
|
14
|
+
This transformer allows you to specify custom clipping bounds for each column
|
|
15
|
+
independently. You can specify only lower bounds, only upper bounds, or both
|
|
16
|
+
for different columns. Columns not specified in either dictionary are left unchanged.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
lower_bounds : dict of str to float, optional
|
|
21
|
+
Dictionary mapping column names to their lower bounds.
|
|
22
|
+
Values below the lower bound will be clipped to the lower bound.
|
|
23
|
+
Default is None (no lower bounds).
|
|
24
|
+
upper_bounds : dict of str to float, optional
|
|
25
|
+
Dictionary mapping column names to their upper bounds.
|
|
26
|
+
Values above the upper bound will be clipped to the upper bound.
|
|
27
|
+
Default is None (no upper bounds).
|
|
28
|
+
inplace : bool, default=True
|
|
29
|
+
If True, clip values in the original columns.
|
|
30
|
+
If False, create new columns with the suffix '__clip_custom'.
|
|
31
|
+
drop_columns : bool, default=True
|
|
32
|
+
If True and inplace=False, drop the original columns after clipping.
|
|
33
|
+
If False and inplace=False, keep both original and clipped columns.
|
|
34
|
+
Ignored if inplace=True.
|
|
35
|
+
|
|
36
|
+
Attributes
|
|
37
|
+
----------
|
|
38
|
+
_columns : list of str
|
|
39
|
+
List of columns that will be clipped (union of lower_bounds and upper_bounds keys).
|
|
40
|
+
_bounds_map : dict of str to tuple
|
|
41
|
+
Mapping of column names to (lower_bound, upper_bound) tuples.
|
|
42
|
+
None values indicate no bound on that side.
|
|
43
|
+
|
|
44
|
+
Examples
|
|
45
|
+
--------
|
|
46
|
+
>>> import polars as pl
|
|
47
|
+
>>> from gators.clippers import CustomClipper
|
|
48
|
+
|
|
49
|
+
Clip with both lower and upper bounds:
|
|
50
|
+
|
|
51
|
+
>>> X = pl.DataFrame({
|
|
52
|
+
... "age": [-5, 25, 150],
|
|
53
|
+
... "salary": [-1000, 50000, 2000000]
|
|
54
|
+
... })
|
|
55
|
+
>>> clipper = CustomClipper(
|
|
56
|
+
... lower_bounds={"age": 0, "salary": 0},
|
|
57
|
+
... upper_bounds={"age": 120, "salary": 1000000}
|
|
58
|
+
... )
|
|
59
|
+
>>> clipper.fit_transform(X)
|
|
60
|
+
shape: (3, 2)
|
|
61
|
+
┌─────┬─────────┐
|
|
62
|
+
│ age ┆ salary │
|
|
63
|
+
│ --- ┆ --- │
|
|
64
|
+
│ f64 ┆ f64 │
|
|
65
|
+
╞═════╪═════════╡
|
|
66
|
+
│ 0.0 ┆ 0.0 │
|
|
67
|
+
│ 25.0┆ 50000.0 │
|
|
68
|
+
│ 120.0┆1000000.0│
|
|
69
|
+
└─────┴─────────┘
|
|
70
|
+
|
|
71
|
+
Clip with only lower bounds:
|
|
72
|
+
|
|
73
|
+
>>> clipper = CustomClipper(lower_bounds={"age": 0})
|
|
74
|
+
>>> clipper.fit_transform(X)
|
|
75
|
+
shape: (3, 2)
|
|
76
|
+
┌─────┬─────────┐
|
|
77
|
+
│ age ┆ salary │
|
|
78
|
+
│ --- ┆ --- │
|
|
79
|
+
│ f64 ┆ f64 │
|
|
80
|
+
╞═════╪═════════╡
|
|
81
|
+
│ 0.0 ┆ -1000.0 │
|
|
82
|
+
│ 25.0┆ 50000.0 │
|
|
83
|
+
│ 150.0┆2000000.0│
|
|
84
|
+
└─────┴─────────┘
|
|
85
|
+
|
|
86
|
+
Create new columns instead of modifying in place:
|
|
87
|
+
|
|
88
|
+
>>> clipper = CustomClipper(
|
|
89
|
+
... lower_bounds={"age": 0},
|
|
90
|
+
... upper_bounds={"age": 120},
|
|
91
|
+
... inplace=False
|
|
92
|
+
... )
|
|
93
|
+
>>> clipper.fit_transform(X)
|
|
94
|
+
shape: (3, 2)
|
|
95
|
+
┌──────────────────┬─────────┐
|
|
96
|
+
│ age__clip_custom ┆ salary │
|
|
97
|
+
│ --- ┆ --- │
|
|
98
|
+
│ f64 ┆ f64 │
|
|
99
|
+
╞══════════════════╪═════════╡
|
|
100
|
+
│ 0.0 ┆ -1000.0 │
|
|
101
|
+
│ 25.0 ┆ 50000.0 │
|
|
102
|
+
│ 120.0 ┆2000000.0│
|
|
103
|
+
└──────────────────┴─────────┘
|
|
104
|
+
|
|
105
|
+
Notes
|
|
106
|
+
-----
|
|
107
|
+
- Non-numeric columns are automatically ignored.
|
|
108
|
+
- Columns not specified in either bounds dictionary are left unchanged.
|
|
109
|
+
- You can specify bounds for only some columns while leaving others untouched.
|
|
110
|
+
- If a column appears in both dictionaries, both bounds are applied.
|
|
111
|
+
|
|
112
|
+
See Also
|
|
113
|
+
--------
|
|
114
|
+
GaussianClipper : Clip values based on mean and standard deviation.
|
|
115
|
+
QuantileClipper : Clip values based on quantiles.
|
|
116
|
+
MADClipper : Clip values based on median absolute deviation.
|
|
117
|
+
IQRClipper : Clip values based on interquartile range.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
lower_bounds: Optional[Dict[str, float]] = Field(default=None)
|
|
121
|
+
upper_bounds: Optional[Dict[str, float]] = Field(default=None)
|
|
122
|
+
inplace: bool = Field(default=True)
|
|
123
|
+
drop_columns: bool = Field(default=True)
|
|
124
|
+
_columns: list = PrivateAttr(default_factory=list)
|
|
125
|
+
_bounds_map: Dict[str, tuple] = PrivateAttr(default_factory=dict)
|
|
126
|
+
|
|
127
|
+
@field_validator("lower_bounds", "upper_bounds")
|
|
128
|
+
@classmethod
|
|
129
|
+
def validate_bounds(cls, v):
|
|
130
|
+
"""Validate that bounds are dictionaries with string keys and numeric values."""
|
|
131
|
+
if v is not None:
|
|
132
|
+
if not isinstance(v, dict):
|
|
133
|
+
raise TypeError("Bounds must be a dictionary")
|
|
134
|
+
if not all(isinstance(k, str) for k in v.keys()):
|
|
135
|
+
raise TypeError("All keys in bounds must be strings (column names)")
|
|
136
|
+
if not all(isinstance(val, (int, float)) for val in v.values()):
|
|
137
|
+
raise TypeError("All values in bounds must be numeric")
|
|
138
|
+
return v
|
|
139
|
+
|
|
140
|
+
def fit(self, X: pl.DataFrame, y: Optional[pl.Series] = None) -> "CustomClipper":
|
|
141
|
+
"""Fit the clipper by identifying columns to clip.
|
|
142
|
+
|
|
143
|
+
Parameters
|
|
144
|
+
----------
|
|
145
|
+
X : pl.DataFrame
|
|
146
|
+
Input DataFrame.
|
|
147
|
+
y : pl.Series, optional
|
|
148
|
+
Target values (ignored, present for sklearn compatibility).
|
|
149
|
+
|
|
150
|
+
Returns
|
|
151
|
+
-------
|
|
152
|
+
self : CustomClipper
|
|
153
|
+
Fitted clipper.
|
|
154
|
+
|
|
155
|
+
Raises
|
|
156
|
+
------
|
|
157
|
+
ValueError
|
|
158
|
+
If no bounds are specified or if specified columns don't exist in X.
|
|
159
|
+
"""
|
|
160
|
+
if self.lower_bounds is None and self.upper_bounds is None:
|
|
161
|
+
raise ValueError("At least one of lower_bounds or upper_bounds must be specified")
|
|
162
|
+
|
|
163
|
+
# Get all columns that have bounds specified
|
|
164
|
+
lower_cols = set(self.lower_bounds.keys()) if self.lower_bounds else set()
|
|
165
|
+
upper_cols = set(self.upper_bounds.keys()) if self.upper_bounds else set()
|
|
166
|
+
all_bound_cols = lower_cols | upper_cols
|
|
167
|
+
|
|
168
|
+
# Check that all specified columns exist in X
|
|
169
|
+
missing_cols = all_bound_cols - set(X.columns)
|
|
170
|
+
if missing_cols:
|
|
171
|
+
raise ValueError(f"Columns specified in bounds not found in DataFrame: {missing_cols}")
|
|
172
|
+
|
|
173
|
+
# Filter to only numeric columns
|
|
174
|
+
numeric_cols = set(X.select(cs.numeric()).columns)
|
|
175
|
+
self._columns = sorted(all_bound_cols & numeric_cols)
|
|
176
|
+
|
|
177
|
+
# Create bounds map: column -> (lower_bound, upper_bound)
|
|
178
|
+
self._bounds_map = {}
|
|
179
|
+
for col in self._columns:
|
|
180
|
+
lower = self.lower_bounds.get(col) if self.lower_bounds else None
|
|
181
|
+
upper = self.upper_bounds.get(col) if self.upper_bounds else None
|
|
182
|
+
self._bounds_map[col] = (lower, upper)
|
|
183
|
+
|
|
184
|
+
return self
|
|
185
|
+
|
|
186
|
+
def transform(self, X: pl.DataFrame) -> pl.DataFrame:
|
|
187
|
+
"""Clip values using the custom bounds.
|
|
188
|
+
|
|
189
|
+
Parameters
|
|
190
|
+
----------
|
|
191
|
+
X : pl.DataFrame
|
|
192
|
+
Input DataFrame to clip.
|
|
193
|
+
|
|
194
|
+
Returns
|
|
195
|
+
-------
|
|
196
|
+
pl.DataFrame
|
|
197
|
+
DataFrame with clipped values.
|
|
198
|
+
"""
|
|
199
|
+
X_transformed = X.clone()
|
|
200
|
+
|
|
201
|
+
for col in self._columns:
|
|
202
|
+
lower, upper = self._bounds_map[col]
|
|
203
|
+
clipped_col = X_transformed[col].clip(lower, upper)
|
|
204
|
+
|
|
205
|
+
if self.inplace:
|
|
206
|
+
X_transformed = X_transformed.with_columns(clipped_col.alias(col))
|
|
207
|
+
else:
|
|
208
|
+
new_col_name = f"{col}__clip_custom"
|
|
209
|
+
X_transformed = X_transformed.with_columns(clipped_col.alias(new_col_name))
|
|
210
|
+
|
|
211
|
+
# Drop original columns if not inplace and drop_columns is True
|
|
212
|
+
if not self.inplace and self.drop_columns:
|
|
213
|
+
X_transformed = X_transformed.drop(self._columns)
|
|
214
|
+
|
|
215
|
+
return X_transformed
|
|
216
|
+
|
|
217
|
+
def fit_transform(self, X: pl.DataFrame, y: Optional[pl.Series] = None) -> pl.DataFrame:
|
|
218
|
+
"""Fit the clipper and transform the data.
|
|
219
|
+
|
|
220
|
+
Parameters
|
|
221
|
+
----------
|
|
222
|
+
X : pl.DataFrame
|
|
223
|
+
Input DataFrame.
|
|
224
|
+
y : pl.Series, optional
|
|
225
|
+
Target values (ignored, present for sklearn compatibility).
|
|
226
|
+
|
|
227
|
+
Returns
|
|
228
|
+
-------
|
|
229
|
+
pl.DataFrame
|
|
230
|
+
DataFrame with clipped values.
|
|
231
|
+
"""
|
|
232
|
+
return self.fit(X, y).transform(X)
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
from typing import Dict, List, Optional, Tuple
|
|
2
|
+
|
|
3
|
+
import polars as pl
|
|
4
|
+
from pydantic import BaseModel, Field, PrivateAttr
|
|
5
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class GaussianClipper(BaseModel, BaseEstimator, TransformerMixin):
|
|
9
|
+
"""
|
|
10
|
+
Clip numeric values to mean ± n standard deviations.
|
|
11
|
+
|
|
12
|
+
This transformer caps values that are smaller than mean - n*std or larger
|
|
13
|
+
than mean + n*std, where n is the number of standard deviations (n_sigmas).
|
|
14
|
+
Values outside this range are clipped to the boundary values.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
n_sigmas : int, default=3
|
|
19
|
+
Number of standard deviations to use for clipping bounds.
|
|
20
|
+
Must be a positive integer.
|
|
21
|
+
subset : Optional[List[str]], default=None
|
|
22
|
+
List of numeric columns to clip. If None, all numeric columns are selected.
|
|
23
|
+
inplace : bool, default=True
|
|
24
|
+
If True, clip values in the original columns.
|
|
25
|
+
If False, create new columns with suffix '__clip_gaussian'.
|
|
26
|
+
drop_columns : bool, default=True
|
|
27
|
+
If inplace=False, whether to drop the original columns after clipping.
|
|
28
|
+
Ignored when inplace=True.
|
|
29
|
+
|
|
30
|
+
Examples
|
|
31
|
+
--------
|
|
32
|
+
>>> import polars as pl
|
|
33
|
+
>>> from gators.clipping import GaussianClipper
|
|
34
|
+
|
|
35
|
+
>>> # Sample DataFrame with outliers
|
|
36
|
+
>>> X = pl.DataFrame({
|
|
37
|
+
... 'A': [1.0, 2.0, 3.0, 4.0, 100.0], # 100.0 is an outlier
|
|
38
|
+
... 'B': [-50.0, 5.0, 6.0, 7.0, 8.0], # -50.0 is an outlier
|
|
39
|
+
... 'C': [10.0, 20.0, 30.0, 40.0, 50.0]
|
|
40
|
+
... })
|
|
41
|
+
|
|
42
|
+
>>> # Clip using 3 standard deviations (default)
|
|
43
|
+
>>> clipper = GaussianClipper(inplace=False)
|
|
44
|
+
>>> clipper.fit(X)
|
|
45
|
+
GaussianClipper(n_sigmas=3, subset=['A', 'B', 'C'], drop_columns=True, inplace=False)
|
|
46
|
+
>>> transformed_X = clipper.transform(X)
|
|
47
|
+
>>> print(transformed_X)
|
|
48
|
+
shape: (5, 3)
|
|
49
|
+
┌───────────────────┬───────────────────┬───────────────────┐
|
|
50
|
+
│ A__clip_gaussian ┆ B__clip_gaussian ┆ C__clip_gaussian │
|
|
51
|
+
│ --- ┆ --- ┆ --- │
|
|
52
|
+
│ f64 ┆ f64 ┆ f64 │
|
|
53
|
+
╞═══════════════════╪═══════════════════╪═══════════════════╡
|
|
54
|
+
│ 1.0 ┆ -24.8 ┆ 10.0 │
|
|
55
|
+
│ 2.0 ┆ 5.0 ┆ 20.0 │
|
|
56
|
+
│ 3.0 ┆ 6.0 ┆ 30.0 │
|
|
57
|
+
│ 4.0 ┆ 7.0 ┆ 40.0 │
|
|
58
|
+
│ 42.8 ┆ 8.0 ┆ 50.0 │
|
|
59
|
+
└───────────────────┴───────────────────┴───────────────────┘
|
|
60
|
+
|
|
61
|
+
>>> # Clip using 2 standard deviations (more aggressive)
|
|
62
|
+
>>> clipper_2sigma = GaussianClipper(n_sigmas=2, inplace=False)
|
|
63
|
+
>>> clipper_2sigma.fit(X)
|
|
64
|
+
GaussianClipper(n_sigmas=2, subset=['A', 'B', 'C'], drop_columns=True, inplace=False)
|
|
65
|
+
>>> transformed_X_2sigma = clipper_2sigma.transform(X)
|
|
66
|
+
>>> print(transformed_X_2sigma)
|
|
67
|
+
shape: (5, 3)
|
|
68
|
+
┌───────────────────┬───────────────────┬───────────────────┐
|
|
69
|
+
│ A__clip_gaussian ┆ B__clip_gaussian ┆ C__clip_gaussian │
|
|
70
|
+
│ --- ┆ --- ┆ --- │
|
|
71
|
+
│ f64 ┆ f64 ┆ f64 │
|
|
72
|
+
╞═══════════════════╪═══════════════════╪═══════════════════╡
|
|
73
|
+
│ 1.0 ┆ -16.5 ┆ 10.0 │
|
|
74
|
+
│ 2.0 ┆ 5.0 ┆ 20.0 │
|
|
75
|
+
│ 3.0 ┆ 6.0 ┆ 30.0 │
|
|
76
|
+
│ 4.0 ┆ 7.0 ┆ 40.0 │
|
|
77
|
+
│ 28.5 ┆ 8.0 ┆ 50.0 │
|
|
78
|
+
└───────────────────┴───────────────────┴───────────────────┘
|
|
79
|
+
|
|
80
|
+
>>> # Clip with drop_columns=False to keep original columns
|
|
81
|
+
>>> clipper_no_drop = GaussianClipper(n_sigmas=3, drop_columns=False, inplace=False)
|
|
82
|
+
>>> clipper_no_drop.fit(X)
|
|
83
|
+
GaussianClipper(n_sigmas=3, subset=['A', 'B', 'C'], drop_columns=False, inplace=False)
|
|
84
|
+
>>> transformed_X_no_drop = clipper_no_drop.transform(X)
|
|
85
|
+
>>> print(transformed_X_no_drop)
|
|
86
|
+
shape: (5, 6)
|
|
87
|
+
┌───────┬────────┬──────┬───────────────────┬───────────────────┬───────────────────┐
|
|
88
|
+
│ A ┆ B ┆ C ┆ A__clip_gaussian ┆ B__clip_gaussian ┆ C__clip_gaussian │
|
|
89
|
+
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
|
|
90
|
+
│ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
|
|
91
|
+
╞═══════╪════════╪══════╪═══════════════════╪═══════════════════╪═══════════════════╡
|
|
92
|
+
│ 1.0 ┆ -50.0 ┆ 10.0 ┆ 1.0 ┆ -24.8 ┆ 10.0 │
|
|
93
|
+
│ 2.0 ┆ 5.0 ┆ 20.0 ┆ 2.0 ┆ 5.0 ┆ 20.0 │
|
|
94
|
+
│ 3.0 ┆ 6.0 ┆ 30.0 ┆ 3.0 ┆ 6.0 ┆ 30.0 │
|
|
95
|
+
│ 4.0 ┆ 7.0 ┆ 40.0 ┆ 4.0 ┆ 7.0 ┆ 40.0 │
|
|
96
|
+
│ 100.0 ┆ 8.0 ┆ 50.0 ┆ 42.8 ┆ 8.0 ┆ 50.0 │
|
|
97
|
+
└───────┴────────┴──────┴───────────────────┴───────────────────┴───────────────────┘
|
|
98
|
+
|
|
99
|
+
>>> # Clip only a subset of columns
|
|
100
|
+
>>> clipper_subset = GaussianClipper(n_sigmas=3, subset=['A'], inplace=False)
|
|
101
|
+
>>> clipper_subset.fit(X)
|
|
102
|
+
GaussianClipper(n_sigmas=3, subset=['A'], drop_columns=True, inplace=False)
|
|
103
|
+
>>> transformed_X_subset = clipper_subset.transform(X)
|
|
104
|
+
>>> print(transformed_X_subset)
|
|
105
|
+
shape: (5, 3)
|
|
106
|
+
┌────────┬──────┬───────────────────┐
|
|
107
|
+
│ B ┆ C ┆ A__clip_gaussian │
|
|
108
|
+
│ --- ┆ --- ┆ --- │
|
|
109
|
+
│ f64 ┆ f64 ┆ f64 │
|
|
110
|
+
╞════════╪══════╪═══════════════════╡
|
|
111
|
+
│ -50.0 ┆ 10.0 ┆ 1.0 │
|
|
112
|
+
│ 5.0 ┆ 20.0 ┆ 2.0 │
|
|
113
|
+
│ 6.0 ┆ 30.0 ┆ 3.0 │
|
|
114
|
+
│ 7.0 ┆ 40.0 ┆ 4.0 │
|
|
115
|
+
│ 8.0 ┆ 50.0 ┆ 42.8 │
|
|
116
|
+
└────────┴──────┴───────────────────┘
|
|
117
|
+
|
|
118
|
+
>>> # Clip inplace (modifies original columns)
|
|
119
|
+
>>> clipper_inplace = GaussianClipper(n_sigmas=3, inplace=True)
|
|
120
|
+
>>> clipper_inplace.fit(X)
|
|
121
|
+
GaussianClipper(n_sigmas=3, subset=['A', 'B', 'C'], drop_columns=True, inplace=True)
|
|
122
|
+
>>> transformed_X_inplace = clipper_inplace.transform(X)
|
|
123
|
+
>>> print(transformed_X_inplace)
|
|
124
|
+
shape: (5, 3)
|
|
125
|
+
┌───────┬────────┬──────┐
|
|
126
|
+
│ A ┆ B ┆ C │
|
|
127
|
+
│ --- ┆ --- ┆ --- │
|
|
128
|
+
│ f64 ┆ f64 ┆ f64 │
|
|
129
|
+
╞═══════╪════════╪══════╡
|
|
130
|
+
│ 1.0 ┆ -24.8 ┆ 10.0 │
|
|
131
|
+
│ 2.0 ┆ 5.0 ┆ 20.0 │
|
|
132
|
+
│ 3.0 ┆ 6.0 ┆ 30.0 │
|
|
133
|
+
│ 4.0 ┆ 7.0 ┆ 40.0 │
|
|
134
|
+
│ 42.8 ┆ 8.0 ┆ 50.0 │
|
|
135
|
+
└───────┴────────┴──────┘
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
n_sigmas: int = Field(default=3, ge=1)
|
|
139
|
+
subset: Optional[List[str]] = None
|
|
140
|
+
drop_columns: bool = True
|
|
141
|
+
inplace: bool = True
|
|
142
|
+
_clip_bounds: Dict[str, Tuple[float, float]] = PrivateAttr(default_factory=dict)
|
|
143
|
+
_column_mapping: Dict[str, str] = PrivateAttr(default_factory=dict)
|
|
144
|
+
|
|
145
|
+
def fit(self, X: pl.DataFrame, y: Optional[pl.Series] = None) -> "GaussianClipper":
|
|
146
|
+
"""Fit the transformer by computing clipping bounds for each column.
|
|
147
|
+
|
|
148
|
+
Parameters
|
|
149
|
+
----------
|
|
150
|
+
X : pl.DataFrame
|
|
151
|
+
Input DataFrame with numeric columns.
|
|
152
|
+
y : Optional[pl.Series], default=None
|
|
153
|
+
Target series (not used, present for sklearn compatibility).
|
|
154
|
+
|
|
155
|
+
Returns
|
|
156
|
+
-------
|
|
157
|
+
GaussianClipper
|
|
158
|
+
The fitted transformer instance.
|
|
159
|
+
"""
|
|
160
|
+
if not self.subset:
|
|
161
|
+
self.subset = [
|
|
162
|
+
col
|
|
163
|
+
for col, dtype in zip(X.columns, X.dtypes)
|
|
164
|
+
if dtype not in [pl.String, pl.Boolean]
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
if not self.inplace:
|
|
168
|
+
self._column_mapping = {col: f"{col}__clip_gaussian" for col in self.subset}
|
|
169
|
+
|
|
170
|
+
# Compute mean and std for each column in a single pass
|
|
171
|
+
stats = X.select(
|
|
172
|
+
[pl.col(c).mean().alias(f"{c}_mean") for c in self.subset]
|
|
173
|
+
+ [pl.col(c).std().alias(f"{c}_std") for c in self.subset]
|
|
174
|
+
).row(0)
|
|
175
|
+
|
|
176
|
+
# Extract means and stds
|
|
177
|
+
n_cols = len(self.subset)
|
|
178
|
+
means = stats[:n_cols]
|
|
179
|
+
stds = stats[n_cols:]
|
|
180
|
+
|
|
181
|
+
# Compute clipping bounds: [mean - n*std, mean + n*std]
|
|
182
|
+
self._clip_bounds = {
|
|
183
|
+
col: (mean - self.n_sigmas * std, mean + self.n_sigmas * std)
|
|
184
|
+
for col, mean, std in zip(self.subset, means, stds)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def transform(self, X: pl.DataFrame) -> pl.DataFrame:
|
|
190
|
+
"""Transform the input DataFrame by clipping values to mean ± n*std.
|
|
191
|
+
|
|
192
|
+
Parameters
|
|
193
|
+
----------
|
|
194
|
+
X : pl.DataFrame
|
|
195
|
+
Input DataFrame with numeric columns.
|
|
196
|
+
|
|
197
|
+
Returns
|
|
198
|
+
-------
|
|
199
|
+
pl.DataFrame
|
|
200
|
+
DataFrame with clipped numeric columns.
|
|
201
|
+
"""
|
|
202
|
+
# Build all transformations at once
|
|
203
|
+
if self.inplace:
|
|
204
|
+
transformations = [
|
|
205
|
+
pl.col(col).clip(
|
|
206
|
+
lower_bound=self._clip_bounds[col][0], upper_bound=self._clip_bounds[col][1]
|
|
207
|
+
)
|
|
208
|
+
for col in self.subset
|
|
209
|
+
]
|
|
210
|
+
else:
|
|
211
|
+
transformations = [
|
|
212
|
+
pl.col(col)
|
|
213
|
+
.clip(lower_bound=self._clip_bounds[col][0], upper_bound=self._clip_bounds[col][1])
|
|
214
|
+
.alias(new)
|
|
215
|
+
for col, new in self._column_mapping.items()
|
|
216
|
+
]
|
|
217
|
+
|
|
218
|
+
X = X.with_columns(transformations)
|
|
219
|
+
|
|
220
|
+
if not self.inplace and self.drop_columns:
|
|
221
|
+
return X.drop(self.subset)
|
|
222
|
+
return X
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
from typing import Dict, List, Optional, Tuple
|
|
2
|
+
|
|
3
|
+
import polars as pl
|
|
4
|
+
from pydantic import BaseModel, Field, PrivateAttr
|
|
5
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class IQRClipper(BaseModel, BaseEstimator, TransformerMixin):
|
|
9
|
+
"""
|
|
10
|
+
Clip numeric values based on Interquartile Range (IQR).
|
|
11
|
+
|
|
12
|
+
This transformer caps values that fall outside the range
|
|
13
|
+
[Q1 - n_iqrs*IQR, Q3 + n_iqrs*IQR], where Q1 and Q3 are the first and
|
|
14
|
+
third quartiles, and IQR = Q3 - Q1. This is a robust method commonly
|
|
15
|
+
used for outlier detection (n_iqrs=1.5 is the standard for box plots).
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
n_iqrs : float, default=1.5
|
|
20
|
+
Number of IQRs beyond Q1/Q3 to use for clipping bounds.
|
|
21
|
+
Must be a positive number. Common values:
|
|
22
|
+
- 1.5: Standard box plot outlier threshold
|
|
23
|
+
- 3.0: Extreme outlier threshold
|
|
24
|
+
subset : Optional[List[str]], default=None
|
|
25
|
+
List of numeric columns to clip. If None, all numeric columns are selected.
|
|
26
|
+
inplace : bool, default=True
|
|
27
|
+
If True, clip values in the original columns.
|
|
28
|
+
If False, create new columns with suffix '__clip_iqr'.
|
|
29
|
+
drop_columns : bool, default=True
|
|
30
|
+
If inplace=False, whether to drop the original columns after clipping.
|
|
31
|
+
Ignored when inplace=True.
|
|
32
|
+
|
|
33
|
+
Examples
|
|
34
|
+
--------
|
|
35
|
+
>>> import polars as pl
|
|
36
|
+
>>> from gators.clipping import IQRClipper
|
|
37
|
+
|
|
38
|
+
>>> # Sample DataFrame with outliers
|
|
39
|
+
>>> X = pl.DataFrame({
|
|
40
|
+
... 'A': [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 100.0],
|
|
41
|
+
... 'B': [-100.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0],
|
|
42
|
+
... })
|
|
43
|
+
|
|
44
|
+
>>> # Clip using 1.5 IQRs (default, standard box plot threshold)
|
|
45
|
+
>>> clipper = IQRClipper(inplace=False)
|
|
46
|
+
>>> clipper.fit(X)
|
|
47
|
+
IQRClipper(n_iqrs=1.5, subset=['A', 'B'], drop_columns=True, inplace=False)
|
|
48
|
+
>>> transformed_X = clipper.transform(X)
|
|
49
|
+
>>> print(transformed_X)
|
|
50
|
+
shape: (12, 2)
|
|
51
|
+
┌──────────────┬──────────────┐
|
|
52
|
+
│ A__clip_iqr ┆ B__clip_iqr │
|
|
53
|
+
│ --- ┆ --- │
|
|
54
|
+
│ f64 ┆ f64 │
|
|
55
|
+
╞══════════════╪══════════════╡
|
|
56
|
+
│ 10.0 ┆ 1.25 │
|
|
57
|
+
│ 11.0 ┆ 10.0 │
|
|
58
|
+
│ 12.0 ┆ 11.0 │
|
|
59
|
+
│ 13.0 ┆ 12.0 │
|
|
60
|
+
│ 14.0 ┆ 13.0 │
|
|
61
|
+
│ 15.0 ┆ 14.0 │
|
|
62
|
+
│ 16.0 ┆ 15.0 │
|
|
63
|
+
│ 17.0 ┆ 16.0 │
|
|
64
|
+
│ 18.0 ┆ 17.0 │
|
|
65
|
+
│ 19.0 ┆ 18.0 │
|
|
66
|
+
│ 20.0 ┆ 19.0 │
|
|
67
|
+
│ 28.75 ┆ 20.0 │
|
|
68
|
+
└──────────────┴──────────────┘
|
|
69
|
+
|
|
70
|
+
>>> # More conservative clipping with 3 IQRs
|
|
71
|
+
>>> clipper_3iqr = IQRClipper(n_iqrs=3.0, inplace=False)
|
|
72
|
+
>>> clipper_3iqr.fit(X)
|
|
73
|
+
IQRClipper(n_iqrs=3.0, subset=['A', 'B'], drop_columns=True, inplace=False)
|
|
74
|
+
>>> transformed_X_3iqr = clipper_3iqr.transform(X)
|
|
75
|
+
>>> print(transformed_X_3iqr)
|
|
76
|
+
shape: (12, 2)
|
|
77
|
+
┌──────────────┬──────────────┐
|
|
78
|
+
│ A__clip_iqr ┆ B__clip_iqr │
|
|
79
|
+
│ --- ┆ --- │
|
|
80
|
+
│ f64 ┆ f64 │
|
|
81
|
+
╞══════════════╪══════════════╡
|
|
82
|
+
│ 10.0 ┆ -15.0 │
|
|
83
|
+
│ 11.0 ┆ 10.0 │
|
|
84
|
+
│ 12.0 ┆ 11.0 │
|
|
85
|
+
│ 13.0 ┆ 12.0 │
|
|
86
|
+
│ 14.0 ┆ 13.0 │
|
|
87
|
+
│ 15.0 ┆ 14.0 │
|
|
88
|
+
│ 16.0 ┆ 15.0 │
|
|
89
|
+
│ 17.0 ┆ 16.0 │
|
|
90
|
+
│ 18.0 ┆ 17.0 │
|
|
91
|
+
│ 19.0 ┆ 18.0 │
|
|
92
|
+
│ 20.0 ┆ 19.0 │
|
|
93
|
+
│ 43.0 ┆ 20.0 │
|
|
94
|
+
└──────────────┴──────────────┘
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
n_iqrs: float = Field(default=1.5, gt=0.0)
|
|
98
|
+
subset: Optional[List[str]] = None
|
|
99
|
+
drop_columns: bool = True
|
|
100
|
+
inplace: bool = True
|
|
101
|
+
_clip_bounds: Dict[str, Tuple[float, float]] = PrivateAttr(default_factory=dict)
|
|
102
|
+
_column_mapping: Dict[str, str] = PrivateAttr(default_factory=dict)
|
|
103
|
+
|
|
104
|
+
def fit(self, X: pl.DataFrame, y: Optional[pl.Series] = None) -> "IQRClipper":
|
|
105
|
+
"""Fit the transformer by computing IQR-based clipping bounds.
|
|
106
|
+
|
|
107
|
+
Parameters
|
|
108
|
+
----------
|
|
109
|
+
X : pl.DataFrame
|
|
110
|
+
Input DataFrame with numeric columns.
|
|
111
|
+
y : Optional[pl.Series], default=None
|
|
112
|
+
Target series (not used, present for sklearn compatibility).
|
|
113
|
+
|
|
114
|
+
Returns
|
|
115
|
+
-------
|
|
116
|
+
IQRClipper
|
|
117
|
+
The fitted transformer instance.
|
|
118
|
+
"""
|
|
119
|
+
if not self.subset:
|
|
120
|
+
self.subset = [
|
|
121
|
+
col
|
|
122
|
+
for col, dtype in zip(X.columns, X.dtypes)
|
|
123
|
+
if dtype not in [pl.String, pl.Boolean]
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
if not self.inplace:
|
|
127
|
+
self._column_mapping = {col: f"{col}__clip_iqr" for col in self.subset}
|
|
128
|
+
|
|
129
|
+
# Compute Q1, Q3, and IQR for each column
|
|
130
|
+
for col in self.subset:
|
|
131
|
+
q1 = X[col].quantile(0.25)
|
|
132
|
+
q3 = X[col].quantile(0.75)
|
|
133
|
+
iqr = q3 - q1
|
|
134
|
+
|
|
135
|
+
# Clipping bounds: [Q1 - n_iqrs*IQR, Q3 + n_iqrs*IQR]
|
|
136
|
+
lower_bound = q1 - self.n_iqrs * iqr
|
|
137
|
+
upper_bound = q3 + self.n_iqrs * iqr
|
|
138
|
+
self._clip_bounds[col] = (lower_bound, upper_bound)
|
|
139
|
+
|
|
140
|
+
return self
|
|
141
|
+
|
|
142
|
+
def transform(self, X: pl.DataFrame) -> pl.DataFrame:
|
|
143
|
+
"""Transform the input DataFrame by clipping values based on IQR.
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
X : pl.DataFrame
|
|
148
|
+
Input DataFrame with numeric columns.
|
|
149
|
+
|
|
150
|
+
Returns
|
|
151
|
+
-------
|
|
152
|
+
pl.DataFrame
|
|
153
|
+
DataFrame with clipped numeric columns.
|
|
154
|
+
"""
|
|
155
|
+
# Build all transformations at once
|
|
156
|
+
if self.inplace:
|
|
157
|
+
transformations = [
|
|
158
|
+
pl.col(col).clip(
|
|
159
|
+
lower_bound=self._clip_bounds[col][0], upper_bound=self._clip_bounds[col][1]
|
|
160
|
+
)
|
|
161
|
+
for col in self.subset
|
|
162
|
+
]
|
|
163
|
+
else:
|
|
164
|
+
transformations = [
|
|
165
|
+
pl.col(col)
|
|
166
|
+
.clip(lower_bound=self._clip_bounds[col][0], upper_bound=self._clip_bounds[col][1])
|
|
167
|
+
.alias(new)
|
|
168
|
+
for col, new in self._column_mapping.items()
|
|
169
|
+
]
|
|
170
|
+
|
|
171
|
+
X = X.with_columns(transformations)
|
|
172
|
+
|
|
173
|
+
if not self.inplace and self.drop_columns:
|
|
174
|
+
return X.drop(self.subset)
|
|
175
|
+
return X
|