From 1b7b4b9cad495955000dadd78cf482e07907bdc2 Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Tue, 25 Aug 2026 17:08:11 +0200 Subject: [PATCH 1/2] Migrate BaseDiscretiser to narwhals, add polars support Shared base for ArbitraryDiscretiser, EqualFrequencyDiscretiser, EqualWidthDiscretiser and GeometricWidthDiscretiser (not DecisionTreeDiscretiser, which extends a different base). Only transform() needed migrating - _fit_setup(), _get_feature_names_in() and _check_transform_input_and_state() are inherited unchanged from BaseNumericalTransformer, already fully narwhals-migrated. transform()'s only pandas dependency was pd.cut, applied per column to sort values into the bins already fixed by fit() (binner_dict_). Replaced it with a plain numpy implementation: pandas.cut is itself built on bins.searchsorted() internally (verified against pandas 3.0's _bins_to_cuts source), so np.searchsorted + the same include_lowest index-1 special case reproduces its bin-index logic exactly, with no per-backend branch needed - values come from nw_X.get_column(feature).to_numpy() regardless of backend, and results are re-attached via nw.new_series()/with_columns(), so the same code path runs for pandas and polars. Benchmarked old pd.cut vs the new numpy+narwhals path at 10k/50k/100k rows x 1/2/10 columns: - return_boundaries=False (bin codes): narwhals-on-pandas lands at ~1.0-1.2x of pandas-native at realistic sizes (50k-100k rows, the ~1.9x seen only at the smallest 10k-row/1-col case is fixed per-call overhead, sub-millisecond either way) - minimal loss, merged into a single path, no is_pandas split. narwhals-on-polars is ~1.0-1.3x *faster* than pandas-native at every size tested. - return_boundaries=True (interval-label strings): the numpy path is 12-20x faster than pd.cut on pandas itself (e.g. 100k rows x 10 cols: 647ms old vs 40ms new) - pd.cut's Categorical/IntervalIndex machinery has heavy per-call overhead that np.searchsorted plus plain string formatting avoids entirely. polars is ~1.2x faster still than the new pandas path. Given both branches favour or are at parity with a single numpy-driven path, there was no case for a pandas fast-path split here. return_boundaries=True's interval-label formatting ("(lower, upper]" text, e.g. "(-0.001, 20.0]") replicates pandas.cut's _round_frac/_infer_precision/lowest-edge-adjustment algorithm in pure numpy so it works identically on both backends - verified against real pd.cut(...).astype(str) output across positive/negative/duplicate- inducing/inf-edge bins, and against the California housing dataset used in the existing test. return_object=True now builds a nw.Object column (narwhals' cross-backend equivalent of pandas' "O" dtype, already used by variable_handling for categorical-column detection) instead of a pandas-only astype("O") call. Verified: tests/test_discretisation full suite unchanged (109 passed, 5 pre-existing failures in test_check_estimator_discretisers.py - sklearn's check_estimator feeds raw numpy arrays, which check_X() has rejected since the narwhals migration's dataframe-only contract; reproduced identically on the unmodified file). Manually diffed transform() output against real pd.cut() across ~10 edge cases (NaN, out-of-range values on both ends, negative bins, exact-edge values, precision auto-widening, single bin) plus the three sibling discretisers' documented doctest examples (EqualWidthDiscretiser, ArbitraryDiscretiser, EqualFrequencyDiscretiser value_counts()) - all numerically identical to old pd.cut output; the "Name: x" vs "Name: count" and bare-fit()-repr mismatches those doctests already show are a pre-existing pandas-3.0 doc-staleness issue unrelated to this migration (reproduced on the unmodified files too). flake8 and mypy clean. Module imports with pandas blocked (loaded standalone, since sibling discretiser files in this package are not yet migrated and still import pandas at their own module level). sphinx -W build clean (only the pre-existing unrelated linkcode_resolve warning). test_base_discretizer.py's test_transform is now parametrized over pd.DataFrame/pl.DataFrame per AGENTS.md - its MockClassFit hard-codes binner_dict_ rather than actually fitting, so it needed no pandas-only logic to begin with. The other four discretisers' own test files stay pandas-only for now: their fit() methods still call pd.cut/pd.qcut directly and aren't migrated by this branch. Co-Authored-By: Claude Sonnet 5 --- .../discretisation/base_discretiser.py | 136 +++++++++++++++--- .../test_base_discretizer.py | 41 +++--- 2 files changed, 135 insertions(+), 42 deletions(-) diff --git a/feature_engine/discretisation/base_discretiser.py b/feature_engine/discretisation/base_discretiser.py index 6c61d05d3..8bce3021f 100644 --- a/feature_engine/discretisation/base_discretiser.py +++ b/feature_engine/discretisation/base_discretiser.py @@ -1,7 +1,11 @@ # Authors: Morgan Sell # License: BSD 3 clause -import pandas as pd +from typing import List + +import narwhals as nw +import numpy as np +from narwhals.typing import IntoDataFrame from feature_engine._base_transformers.base_numerical import BaseNumericalTransformer @@ -41,45 +45,133 @@ def __init__( self.return_boundaries = return_boundaries self.precision = precision - def transform(self, X: pd.DataFrame) -> pd.DataFrame: + def transform(self, X: IntoDataFrame) -> IntoDataFrame: """Sort the variable values into the intervals. Parameters ---------- - X: pandas dataframe of shape = [n_samples, n_features] + X: dataframe of shape = [n_samples, n_features] The data to transform. Returns ------- - X_new: pandas dataframe of shape = [n_samples, n_features] + X_new: dataframe of shape = [n_samples, n_features] The transformed data with the discrete variables. """ # check input dataframe and if class was fitted X = self._check_transform_input_and_state(X) - # transform variables + # bin edges are already fixed by fit(), so sorting values into them is a + # plain numpy searchsorted - vectorizable identically for every backend, + # no pandas/polars-specific path needed. + nw_X = nw.from_native(X, eager_only=True) + native_namespace = nw_X.__native_namespace__() + if self.return_boundaries is True: - for feature in self.variables_: - X[feature] = pd.cut( - X[feature], - self.binner_dict_[feature], - precision=self.precision, - include_lowest=True, + new_columns = [ + nw.new_series( + feature, + _bin_labels( + nw_X.get_column(feature).to_numpy(), + self.binner_dict_[feature], + self.precision, + ), + backend=native_namespace, ) - X[self.variables_] = X[self.variables_].astype(str) - + for feature in self.variables_ + ] else: - for feature in self.variables_: - X[feature] = pd.cut( - X[feature], - self.binner_dict_[feature], - labels=False, - include_lowest=True, + # nw.Object mirrors the pandas "O" dtype astype() used to produce, + # and is what feature-engine's categorical encoders detect on + # every narwhals-supported backend (see variable_handling). + dtype = nw.Object if self.return_object is True else None + new_columns = [ + nw.new_series( + feature, + _bin_codes( + nw_X.get_column(feature).to_numpy(), + self.binner_dict_[feature], + self.return_object, + ), + dtype=dtype, + backend=native_namespace, ) + for feature in self.variables_ + ] - # return object - if self.return_object: - X[self.variables_] = X[self.variables_].astype("O") + X = nw_X.with_columns(*new_columns).to_native() return X + + +def _digitize(values: np.ndarray, bins_arr: np.ndarray): + """0-based bin index per value, right-closed intervals with the lowest edge + included - mirrors pandas.cut(bins=bins, include_lowest=True), which is + itself built on this same bins.searchsorted() call. Values outside the + bin range, and NaNs, are flagged via na_mask rather than given a code. + """ + ids = np.asarray(np.searchsorted(bins_arr, values, side="left")) + ids[values == bins_arr[0]] = 1 + na_mask: np.ndarray = np.isnan(values) | (ids == len(bins_arr)) | (ids == 0) + return ids - 1, na_mask + + +def _bin_codes(values: np.ndarray, bins: List[float], return_object: bool): + bins_arr: np.ndarray = np.asarray(bins, dtype=float) + codes, na_mask = _digitize(values, bins_arr) + + # match pandas.cut(labels=False): int codes, upcast to float only when a + # NaN placeholder is actually needed. + if na_mask.any(): + codes = codes.astype(np.float64) + codes[na_mask] = np.nan + if return_object is True: + codes = codes.astype(object) + + return codes + + +def _bin_labels(values: np.ndarray, bins: List[float], precision: int): + bins_arr: np.ndarray = np.asarray(bins, dtype=float) + codes, na_mask = _digitize(values, bins_arr) + + labels = np.asarray(_format_bin_labels(bins_arr, precision), dtype=object) + out: np.ndarray = np.empty(len(values), dtype=object) + out[~na_mask] = labels[codes[~na_mask]] + out[na_mask] = None + + return out + + +def _format_bin_labels(bins_arr: np.ndarray, precision: int) -> List[str]: + """"(lower, upper]" text per bin, replicating pandas.cut's own label + formatting: widen precision until break values are unique, then shrink + the lowest edge so include_lowest values still read as inside the first + interval. + """ + precision = _infer_precision(precision, bins_arr) + breaks = [_round_frac(b, precision) for b in bins_arr] + breaks[0] = breaks[0] - 10 ** (-precision) + return [f"({breaks[i]}, {breaks[i + 1]}]" for i in range(len(breaks) - 1)] + + +def _round_frac(x: float, precision: int) -> float: + if not np.isfinite(x) or x == 0: + return float(x) + frac, whole = np.modf(x) + if whole == 0: + digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision + else: + digits = precision + return float(np.around(x, digits)) + + +def _infer_precision(base_precision: int, bins_arr: np.ndarray) -> int: + # widen precision until every rounded break is unique - otherwise two + # adjacent bins could render with identical label text. + for precision in range(base_precision, 20): + levels = [_round_frac(b, precision) for b in bins_arr] + if len(set(levels)) == len(bins_arr): + return precision + return base_precision diff --git a/tests/test_discretisation/test_base_discretizer.py b/tests/test_discretisation/test_base_discretizer.py index fc8110ff1..f852bf164 100644 --- a/tests/test_discretisation/test_base_discretizer.py +++ b/tests/test_discretisation/test_base_discretizer.py @@ -1,5 +1,6 @@ import numpy as np import pandas as pd +import polars as pl import pytest from sklearn.datasets import fetch_california_housing @@ -38,42 +39,42 @@ def test_correct_param_assignment_at_init(params): class MockClassFit(BaseDiscretiser): def fit(self, X): - california_dataset = fetch_california_housing() - data = pd.DataFrame( - california_dataset.data, columns=california_dataset.feature_names - ) + # bins are hard-coded rather than learnt, so this mock works unchanged + # on both pandas and polars input. self.variables_ = ["HouseAge"] self.binner_dict_ = {"HouseAge": [0, 20, 40, 60, np.inf]} - self.n_features_in_ = data.shape[1] - self.feature_names_in_ = california_dataset.feature_names + self.n_features_in_ = X.shape[1] + self.feature_names_in_ = list(X.columns) return self -def test_transform(): +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_transform(make_df): california_dataset = fetch_california_housing() - data = pd.DataFrame( + data_pd = pd.DataFrame( california_dataset.data, columns=california_dataset.feature_names ) - data_t1 = data.copy() - data_t2 = data.copy() - - # HouseAge is the median house age in the block group. - data_t1["HouseAge"] = pd.cut( - data["HouseAge"], bins=[0, 20, 40, 60, np.inf], include_lowest=True - ) - data_t1["HouseAge"] = data_t1["HouseAge"].astype(str) - data_t2["HouseAge"] = pd.cut( - data["HouseAge"], + # ground truth via pandas.cut: bins are fixed by MockClassFit, so both + # backends must reproduce this exact output. + expected_codes = pd.cut( + data_pd["HouseAge"], bins=[0, 20, 40, 60, np.inf], labels=False, include_lowest=True, + ).to_numpy() + expected_labels = ( + pd.cut(data_pd["HouseAge"], bins=[0, 20, 40, 60, np.inf], include_lowest=True) + .astype(str) + .to_numpy() ) + data = make_df(data_pd) + transformer = MockClassFit(return_boundaries=False) X = transformer.fit_transform(data) - pd.testing.assert_frame_equal(X, data_t2) + assert np.array_equal(X["HouseAge"].to_numpy(), expected_codes) transformer = MockClassFit(return_object=False, return_boundaries=True) X = transformer.fit_transform(data) - pd.testing.assert_frame_equal(X, data_t1) + assert np.array_equal(X["HouseAge"].to_numpy(), expected_labels) From c6f48779a901d42a3b5273d99b97bfee6e12fd14 Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Wed, 26 Aug 2026 00:56:16 +0200 Subject: [PATCH 2/2] Migrate EqualWidthDiscretiser to narwhals, add polars support fit()'s only pandas dependency was pd.cut(bins=int, retbins=True, duplicates="drop"), used purely to compute equal-width bin edges from each variable's min/max (the discretised codes themselves come from transform(), already migrated to numpy searchsorted on the prior base_discretiser branch). Replaced it with _equal_width_edges(): a plain numpy np.linspace(min, max, bins+1), reproducing pandas.cut's own edge computation exactly - verified against pandas 3.0's _nbins_to_bins/_bins_to_cuts source, including the mn==mx 0.1%-range widening for constant columns and the duplicates="drop" collapse for degenerate float edges. fit() now pulls all variables' values in one nw.from_native(X).select(variables_).to_numpy() call (min/max per column via axis=0), instead of one get_column() round-trip per variable, following the pattern already used in CyclicalFeatures.fit(). Benchmarked old pandas-native (pd.cut per column) vs the new narwhals+numpy fit() at 10k/50k/100k rows x 1/2/10 columns: - narwhals-on-pandas is *faster* than the old pd.cut path everywhere except the smallest 10k-row/1-col case (2.58x slower there, but sub-millisecond either way - fixed per-call overhead). At realistic sizes (50k-100k rows) it's 2-6x faster; at 100k rows x 10 cols, 19.3ms (old) vs 3.0ms (new). - narwhals-on-polars is faster still at every size (e.g. 100k x 10: 2.9ms). Given the new path is a speedup rather than a loss on pandas, there was no case for a pandas fast-path split (is_pandas branch) - fit() is a single numpy-driven code path for every backend. Verified binner_dict_ output is numerically identical to the old pd.cut-based fit() across 53 diff cases (random/int/negative values, constant columns at zero/positive/negative, tiny near-duplicate float ranges, two-point and single-value arrays, bins=1) - zero mismatches. Also verified full fit_transform() end-to-end against the class docstring's documented value_counts() output (pre-existing "Name: x" vs "Name: count" pandas-3.0 staleness noted in the base branch is unrelated to this migration) and confirmed the module fit()/transform() round-trip works on polars with pandas import blocked at the interpreter level. tests/test_discretisation/test_equal_width_discretiser.py: converted to one parametrized test per behavior over @pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) per AGENTS.md, replacing the pandas-only tests. Also fixed two vacuous assertions in the original numeric-output test (generator expressions that were checking truthiness of an always-empty filtered sequence, so they passed regardless of correctness) with real value comparisons against pd.cut ground truth, and added a dedicated constant-column case exercising the new mn==mx widening branch that pd.cut used to handle internally. docs/user_guide/discretisation/EqualWidthDiscretiser.rst: verified every existing example (binner_dict_, transformed head, dtypes, return_boundaries output) against real output - all matched, no changes needed to those values. Fixed a pre-existing copy-paste bug (predates this migration) where the "Return bin boundaries" code example set up an EqualFrequencyDiscretiser instead of EqualWidthDiscretiser. Updated the "under the hood" description that referenced pandas.cut specifically, and added a "With polars" section with a verified worked example. Verified: tests/test_discretisation full suite - 116 passed, same 5 pre-existing failures as the unmodified baseline (check_estimator feeds raw numpy arrays, rejected by check_X() since the narwhals migration's dataframe-only contract predates this branch). flake8 and mypy clean. sphinx -W build clean (only the pre-existing unrelated linkcode_resolve warning, confirmed identical on the unmodified baseline). Module imports and runs fit_transform() on polars input with pandas blocked at the builtins.__import__ level. Co-Authored-By: Claude Sonnet 5 --- .../discretisation/EqualWidthDiscretiser.rst | 51 +++++++++++- feature_engine/discretisation/equal_width.py | 52 ++++++++---- .../test_equal_width_discretiser.py | 80 +++++++++++++------ 3 files changed, 136 insertions(+), 47 deletions(-) diff --git a/docs/user_guide/discretisation/EqualWidthDiscretiser.rst b/docs/user_guide/discretisation/EqualWidthDiscretiser.rst index bd149df24..16bfda029 100644 --- a/docs/user_guide/discretisation/EqualWidthDiscretiser.rst +++ b/docs/user_guide/discretisation/EqualWidthDiscretiser.rst @@ -48,9 +48,10 @@ potentially impact the model's performance in this scenario. EqualWidthDiscretiser --------------------- -Feture-engine's :class:`EqualWidthDiscretiser()` applies equal width discretisation to numerical variables. It uses -the `pandas.cut()` function under the hood to find the interval limits and then sort the continuous variables into -the bins. +Feture-engine's :class:`EqualWidthDiscretiser()` applies equal width discretisation to numerical variables. It finds +the interval limits from each variable's minimum and maximum value, then sorts the continuous variables into the +bins. It works with pandas, polars, and any other dataframe library supported by +`narwhals `_. You can specify the variables to be discretised by passing their names in a list when you set up the transformer. Alternatively, :class:`EqualWidthDiscretiser()` will automatically infer the data types and compute the interval limits for all numeric @@ -271,7 +272,7 @@ If we want to output the intervals limits instead of integers, we can set `retur .. code:: python # Set up the discretisation transformer - disc = EqualFrequencyDiscretiser( + disc = EqualWidthDiscretiser( bins=10, variables=['LotArea','GrLivArea'], return_boundaries=True) @@ -301,6 +302,48 @@ While we can't use these variables to train machine learning models, as opposed to the variables discretised into integers, they are very useful in this format for data analysis, and we can use any feature-engine encoder for further processing. +With polars +~~~~~~~~~~~ + +:class:`EqualWidthDiscretiser()` works in the same way with a polars dataframe: + +.. code:: python + + import polars as pl + from feature_engine.discretisation import EqualWidthDiscretiser + + df = pl.DataFrame({ + "x": [10400, 3675, 8640, 11670, 10667, 6120, 9500, 14000, 7200, 5300], + }) + + disc = EqualWidthDiscretiser(bins=5) + + print(disc.fit_transform(df)) + +The resulting values match those found with pandas: + +.. code:: text + + shape: (10, 1) + ┌─────┐ + │ x │ + │ --- │ + │ i64 │ + ╞═════╡ + │ 3 │ + │ 0 │ + │ 2 │ + │ 3 │ + │ 3 │ + │ 1 │ + │ 2 │ + │ 4 │ + │ 1 │ + │ 0 │ + └─────┘ + +`return_object`, `return_boundaries`, and `binner_dict_` work identically to the pandas examples above. + See Also -------- diff --git a/feature_engine/discretisation/equal_width.py b/feature_engine/discretisation/equal_width.py index bab5c5396..bdffc748d 100644 --- a/feature_engine/discretisation/equal_width.py +++ b/feature_engine/discretisation/equal_width.py @@ -3,7 +3,9 @@ from typing import List, Optional, Union -import pandas as pd +import narwhals as nw +import numpy as np +from narwhals.typing import IntoDataFrame, IntoSeries from feature_engine._check_init_parameters.check_init_input_params import ( _check_return_empty_is_bool, @@ -164,14 +166,14 @@ def __init__( self.return_empty = return_empty self.bins = bins - def fit(self, X: pd.DataFrame, y: Optional[pd.Series] = None): + def fit(self, X: IntoDataFrame, y: Optional[IntoSeries] = None): """ Learn the boundaries of the equal width intervals / bins for each variable. Parameters ---------- - X: pandas dataframe of shape = [n_samples, n_features] + X: dataframe of shape = [n_samples, n_features] The training dataset. Can be the entire dataframe, not just the variables to be transformed. y: None @@ -184,23 +186,39 @@ def fit(self, X: pd.DataFrame, y: Optional[pd.Series] = None): # fit binner_dict_ = {} - for var in variables_: - tmp, bins = pd.cut( - x=X[var], - bins=self.bins, - retbins=True, - duplicates="drop", - include_lowest=True, - ) - - # Prepend/Append infinities - bins = list(bins) - bins[0] = float("-inf") - bins[len(bins) - 1] = float("inf") - binner_dict_[var] = bins + if len(variables_) > 0: + # one narwhals call for every variable at once, instead of a + # get_column() round-trip per variable. + arr = nw.from_native(X, eager_only=True).select(variables_).to_numpy() + mins = arr.min(axis=0) + maxs = arr.max(axis=0) + for var, mn, mx in zip(variables_, mins, maxs): + binner_dict_[var] = _equal_width_edges(mn, mx, self.bins) self.binner_dict_ = binner_dict_ self.variables_ = variables_ self._get_feature_names_in(X) return self + + +def _equal_width_edges(mn: float, mx: float, bins: int) -> List[float]: + """Bin-edge computation matching pandas.cut(bins=int, duplicates="drop"): + widen a constant [mn, mx] by 0.1% so linspace still produces positive- + width bins, then collapse duplicate edges the same way. The outer edges + are then clipped to +-inf, same as the pre-migration code did to the + retbins output, so transform() never needs an out-of-range branch. + """ + if mn == mx: + mn = mn - 0.001 * abs(mn) if mn != 0 else -0.001 + mx = mx + 0.001 * abs(mx) if mx != 0 else 0.001 + + edges = np.linspace(mn, mx, bins + 1) + unique_edges = np.unique(edges) + if len(unique_edges) < len(edges) and len(edges) != 2: + edges = unique_edges + + edges_: List[float] = edges.tolist() + edges_[0] = float("-inf") + edges_[-1] = float("inf") + return edges_ diff --git a/tests/test_discretisation/test_equal_width_discretiser.py b/tests/test_discretisation/test_equal_width_discretiser.py index 88782af91..684c6ee29 100644 --- a/tests/test_discretisation/test_equal_width_discretiser.py +++ b/tests/test_discretisation/test_equal_width_discretiser.py @@ -1,23 +1,26 @@ +import numpy as np import pandas as pd +import polars as pl import pytest from sklearn.exceptions import NotFittedError from feature_engine.discretisation import EqualWidthDiscretiser -def test_automatically_find_variables_and_return_as_numeric(df_normal_dist): - # test case 1: automatically select variables, return_object=False +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_automatically_find_variables_and_return_as_numeric(df_normal_dist, make_df): transformer = EqualWidthDiscretiser(bins=10, variables=None, return_object=False) - X = transformer.fit_transform(df_normal_dist) + X = transformer.fit_transform(make_df(df_normal_dist)) - # fit parameters + # ground truth bin edges via pandas.cut, same widening/duplicates-drop + # rules the new fit() replicates in plain numpy. _, bins = pd.cut(x=df_normal_dist["var"], bins=10, retbins=True, duplicates="drop") bins[0] = float("-inf") bins[len(bins) - 1] = float("inf") - # transform output - X_t = [x for x in range(0, 10)] - val_counts = [18, 17, 16, 13, 11, 7, 7, 5, 5, 1] + expected_codes = pd.cut( + df_normal_dist["var"], bins=list(bins), labels=False, include_lowest=True + ).to_numpy() # init params assert transformer.bins == 10 @@ -26,45 +29,70 @@ def test_automatically_find_variables_and_return_as_numeric(df_normal_dist): # fit params assert transformer.variables_ == ["var"] assert transformer.n_features_in_ == 1 - # transform params - assert (transformer.binner_dict_["var"] == bins).all() - assert all(x for x in X["var"].unique() if x not in X_t) - # in equal width discretisation, intervals get different number of values - assert all(x for x in X["var"].value_counts() if x not in val_counts) + assert np.allclose(transformer.binner_dict_["var"], bins) + # transform params: same bin codes on both backends + assert np.array_equal(np.asarray(X["var"]), expected_codes) -def test_automatically_find_variables_and_return_as_object(df_normal_dist): +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_automatically_find_variables_and_return_as_object(df_normal_dist, make_df): transformer = EqualWidthDiscretiser(bins=10, variables=None, return_object=True) - X = transformer.fit_transform(df_normal_dist) - assert X["var"].dtypes == "O" + X = transformer.fit_transform(make_df(df_normal_dist)) + + if isinstance(X, pd.DataFrame): + assert X["var"].dtype == object + else: + assert X["var"].dtype == pl.Object + + +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_constant_variable_produces_single_bin(make_df): + # fit()'s bin-edge widening for a zero-range variable (mn == mx): should + # still fit without error and place every value in the same bin, same as + # pandas.cut(bins=10) on a constant series. + df = pd.DataFrame({"var": [5.0] * 10}) + transformer = EqualWidthDiscretiser(bins=10) + X = transformer.fit_transform(make_df(df)) + + _, bins = pd.cut(x=df["var"], bins=10, retbins=True, duplicates="drop") + bins[0] = float("-inf") + bins[len(bins) - 1] = float("inf") + expected_codes = pd.cut( + df["var"], bins=list(bins), labels=False, include_lowest=True + ).to_numpy() + + assert transformer.binner_dict_["var"][0] == float("-inf") + assert transformer.binner_dict_["var"][-1] == float("inf") + assert np.array_equal(np.asarray(X["var"]), expected_codes) def test_error_when_bins_not_number(): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="bins must be an integer"): EqualWidthDiscretiser(bins="other") def test_error_if_return_object_not_bool(): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="return_object must be True or False"): EqualWidthDiscretiser(return_object="other") -def test_error_if_input_df_contains_na_in_fit(df_na): - # test case 3: when dataset contains na, fit method +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_error_if_input_df_contains_na_in_fit(df_na, make_df): with pytest.raises(ValueError): transformer = EqualWidthDiscretiser() - transformer.fit(df_na) + transformer.fit(make_df(df_na)) -def test_error_if_input_df_contains_na_in_transform(df_vartypes, df_na): - # test case 4: when dataset contains na, transform method +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_error_if_input_df_contains_na_in_transform(df_vartypes, df_na, make_df): with pytest.raises(ValueError): transformer = EqualWidthDiscretiser() - transformer.fit(df_vartypes) - transformer.transform(df_na[["Name", "City", "Age", "Marks", "dob"]]) + transformer.fit(make_df(df_vartypes)) + transformer.transform(make_df(df_na[["Name", "City", "Age", "Marks", "dob"]])) -def test_non_fitted_error(df_vartypes): +@pytest.mark.parametrize("make_df", [pd.DataFrame, pl.DataFrame]) +def test_non_fitted_error(df_vartypes, make_df): with pytest.raises(NotFittedError): transformer = EqualWidthDiscretiser() - transformer.transform(df_vartypes) + transformer.transform(make_df(df_vartypes))