From f8916a000dec834949b7c4fe2001a74cf48d3875 Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:33:33 +0100 Subject: [PATCH] fix(encoding): number mixed-type categories in the int encoder ContinuousOrdinalTransformer sorted the distinct categories with np.unique, which cannot order an int next to a str. A categorical object column such as product codes (101, "A7", 205) therefore made fit, and the default Preprocessor, raise a TypeError. Categories of one type keep np.unique's order. When they cannot be compared, they are ordered by type name and naturally within each type, so the codes stay deterministic. Fixes #177 --- docs/representations/categorical_encoding.md | 3 ++ pretab/encoding/categorical/ordinal.py | 29 +++++++++++++++-- .../test_continuous_ordinal_transformer.py | 32 +++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/docs/representations/categorical_encoding.md b/docs/representations/categorical_encoding.md index 12416df..091f653 100644 --- a/docs/representations/categorical_encoding.md +++ b/docs/representations/categorical_encoding.md @@ -23,6 +23,9 @@ t.transform(np.array([["unseen"]])).ravel() ``` Unseen categories at transform time map to a reserved slot (code `0`) rather than raising. +Codes follow the sorted order of the categories. A column that mixes types which cannot be +compared, such as integer codes and strings in one object column, is ordered by type name and +then naturally within each type. ```{note} Integer encoding imposes an order on the codes. Feed it to models that treat the code as an diff --git a/pretab/encoding/categorical/ordinal.py b/pretab/encoding/categorical/ordinal.py index e3a9226..6c3b5ac 100644 --- a/pretab/encoding/categorical/ordinal.py +++ b/pretab/encoding/categorical/ordinal.py @@ -13,13 +13,38 @@ def _is_missing_value(value) -> bool: return bool(pd.isna(value)) +def _sorted_categories(values: np.ndarray) -> list: + """Return the distinct categories of ``values`` in sorted order. + + Categories of one type keep their natural order (``np.unique``). A column that + mixes types that cannot be compared, such as ints and strings in an object + column, is ordered by type name first and naturally within each type, so the + numbering is still deterministic. + """ + try: + return list(np.unique(values)) + except TypeError: + groups: dict[str, list] = {} + for value in dict.fromkeys(values): + groups.setdefault(type(value).__name__, []).append(value) + ordered = [] + for name in sorted(groups): + try: + ordered.extend(sorted(groups[name])) + except TypeError: + ordered.extend(sorted(groups[name], key=repr)) + return ordered + + class ContinuousOrdinalTransformer(RepresentationSpecMixin, TransformerMixin, BaseEstimator): """Encode categorical features as continuous integer values. Each unique category within a feature is assigned an integer based on its sorted order. Unknown, missing (``None``, ``pd.NA`` or NaN), or unseen categories are mapped to ``0``. This is useful for models that can only handle numerical - input. + input. A feature that mixes types which cannot be compared (e.g. ints and + strings in one object column) is ordered by type name, then naturally within + each type. Attributes ---------- @@ -76,7 +101,7 @@ def fit(self, X, y=None): # Missing values are excluded before sorting: np.unique # cannot compare a NaN or None against a string category. non_missing = np.array([v for v in column if not _is_missing_value(v)], dtype=object) - categories = np.unique(non_missing) if non_missing.size else np.array([], dtype=object) + categories = _sorted_categories(non_missing) if non_missing.size else [] mapping = {category: i + 1 for i, category in enumerate(categories)} mapping[None] = 0 # Assign 0 to unknown/missing values self.mapping_.append(mapping) diff --git a/tests/encoding/categorical/test_continuous_ordinal_transformer.py b/tests/encoding/categorical/test_continuous_ordinal_transformer.py index 2997c39..3960b19 100644 --- a/tests/encoding/categorical/test_continuous_ordinal_transformer.py +++ b/tests/encoding/categorical/test_continuous_ordinal_transformer.py @@ -66,3 +66,35 @@ def test_continuous_ordinal_all_missing_and_transform_time_missing(): clean = ContinuousOrdinalTransformer().fit(pd.DataFrame({"c": ["a", "b"]})) transformed = clean.transform(pd.DataFrame({"c": [pd.NA, "unseen", "a"]})) assert transformed.ravel().tolist() == [0, 0, 1] + + +def test_continuous_ordinal_numbers_mixed_type_categories(): + """np.unique cannot sort ints next to strings, so fit raised TypeError.""" + X = pd.DataFrame({"c": pd.Series([10, "b", 2, "a", np.nan, 2], dtype=object)}) + transformer = ContinuousOrdinalTransformer().fit(X) + + assert transformer.mapping_[0] == {2: 1, 10: 2, "a": 3, "b": 4, None: 0} + transformed = transformer.transform(pd.DataFrame({"c": pd.Series([2, "a", 10, "unseen", None], dtype=object)})) + assert transformed.ravel().tolist() == [1, 3, 2, 0, 0] + + +def test_continuous_ordinal_keeps_the_sorted_order_of_one_type(): + X = pd.DataFrame({"c": [10, 2, 1, 2]}) + assert ContinuousOrdinalTransformer().fit_transform(X).ravel().tolist() == [3, 2, 1, 2] + + +def test_preprocessor_encodes_a_mixed_type_categorical_column(): + import json + + from pretab import Preprocessor + + rng = np.random.default_rng(0) + # One most frequent category: scikit-learn 1.6's SimpleImputer cannot break a + # most-frequent tie between an int and a str (later versions can). + X = pd.DataFrame({"code": pd.Series([1, "a", "a", 2, "b", 10] * 10, dtype=object), "x": rng.normal(size=60)}) + pre = Preprocessor(numerical_method="minmax").fit(X, rng.normal(size=60)) + + assert pre.categorical_features_ == ["code"] + out = pre.transform(X, return_array=True) + restored = Preprocessor.from_spec(json.loads(json.dumps(pre.to_spec()))) + np.testing.assert_array_equal(restored.transform(X, return_array=True), out)