From a7f25be3b13aa7cb4c1c7a8c133534c01118df3f Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:42:57 +0100 Subject: [PATCH] fix(preprocessor): encode an all-missing categorical batch as object NaN Without categorical imputation, _CategoricalMissingNormalizer is the only step before the one-hot encoder and passed non-object input through unchanged. pandas and polars type an all-missing column as float, so one serving row with an unknown category reached an encoder fitted on string categories and failed with a TypeError from np.isnan. The normalizer now returns a batch in which every value is missing as an object array of NaN. The encoder matches it to its missing category (or ignores it as unknown) for string and numeric categories alike. No fitted state is added, so fingerprints are unchanged. Fixes #159 --- pretab/preprocessing/missing.py | 12 +++++- tests/integration/test_pandas_missing.py | 51 ++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/pretab/preprocessing/missing.py b/pretab/preprocessing/missing.py index 70b250d..ae211f8 100644 --- a/pretab/preprocessing/missing.py +++ b/pretab/preprocessing/missing.py @@ -12,7 +12,12 @@ class _CategoricalMissingNormalizer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): - """Normalize object missing markers without changing numeric or sparse inputs.""" + """Normalize object missing markers without changing numeric or sparse inputs. + + A batch in which every value is missing is returned as an ``object`` array of + NaN, whatever its dtype: pandas and polars type an all-missing column as + float, which an encoder fitted on string categories cannot compare with them. + """ def fit(self, X, y=None): validate_data(self, X, skip_check_array=True) @@ -28,6 +33,11 @@ def transform(self, X): # rejects nonzero fill values and changes OneHotEncoder's input contract. return X.copy() values = check_array(X, dtype=None, ensure_all_finite=False, copy=True) # type: ignore[arg-type] + if values.dtype.kind != "O" and values.size and pd.isna(values).all(): + # An all-missing categorical column (e.g. one serving row with an unknown + # value) arrives as float NaN; as object NaN it matches the encoder's + # missing category whether the categories were strings or numbers. + values = values.astype(object) if values.dtype.kind == "O": return np.where(pd.isna(values), np.nan, values) return X.copy() if isinstance(X, pd.DataFrame) else values diff --git a/tests/integration/test_pandas_missing.py b/tests/integration/test_pandas_missing.py index 0cf2411..6981e19 100644 --- a/tests/integration/test_pandas_missing.py +++ b/tests/integration/test_pandas_missing.py @@ -150,3 +150,54 @@ def test_propagate_none_retains_raw_marker(marker, return_array): else: assert np.isnan(result[1, 0]) pd.testing.assert_frame_equal(frame, original) + + +_UNIMPUTED_OPTIONS = [ + {"missing_policy": "propagate"}, + {"categorical_imputation": None}, + {"categorical_imputation": None, "add_missing_indicator": True}, + {"missing_policy": "separate_state"}, +] + + +@pytest.mark.parametrize("categorical_method", ["one-hot", "int"]) +@pytest.mark.parametrize("missing_options", _UNIMPUTED_OPTIONS) +def test_all_missing_categorical_batch_matches_object_nan(categorical_method, missing_options): + """pandas types an all-missing column as float64, so one serving row with an + unknown category crashed the one-hot encoder fitted on string categories.""" + pre = Preprocessor(numerical_method="minmax", categorical_method=categorical_method, **missing_options) + pre.fit(_frame()) + row = pd.DataFrame({"x": [0.3], "c": [np.nan]}) + assert row["c"].dtype == np.float64 + + expected = pre.transform(row.astype({"c": object}), return_array=True) + np.testing.assert_array_equal(pre.transform(row, return_array=True), expected) + + +@pytest.mark.parametrize("with_missing_category", [True, False]) +@pytest.mark.parametrize("categories", ["strings", "integers"]) +def test_all_missing_one_hot_batch_encodes_as_missing_or_unknown(with_missing_category, categories): + codes = [3, 1, 2, 3, 2, 3] if categories == "integers" else ["a", "b", "c", "a", "c", "a"] + frame = pd.DataFrame({"x": [0.1, 0.4, 0.2, 0.9, 0.5, 0.7], "c": pd.Series(codes, dtype=object)}) + if with_missing_category: + frame.loc[1, "c"] = np.nan + pre = Preprocessor( + numerical_method="minmax", categorical_method="one-hot", missing_policy="propagate", cat_cutoff=10 + ).fit(frame) + names = list(pre.get_feature_names_out()) + + out = pre.transform(pd.DataFrame({"x": [0.3, 0.6], "c": [np.nan, np.nan]}), return_array=True) + + category_columns = [i for i, name in enumerate(names) if name.startswith("cat_c_")] + expected = [1.0 if names[i] == "cat_c_nan" else 0.0 for i in category_columns] + np.testing.assert_array_equal(out[:, category_columns], [expected, expected]) + + +def test_all_missing_polars_column_is_encoded_like_pandas(): + pl = pytest.importorskip("polars") + pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot", missing_policy="propagate") + pre.fit(_frame()) + row = pl.DataFrame({"x": [0.3], "c": [None]}) + + expected = pre.transform(pd.DataFrame({"x": [0.3], "c": pd.Series([np.nan], dtype=object)}), return_array=True) + np.testing.assert_array_equal(pre.transform(row, return_array=True), expected)