Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions feature_engine/encoding/one_hot.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ def fit(self, X: pd.DataFrame, y: Optional[pd.Series] = None):

self.variables_ = variables_
self._get_feature_names_in(X)
self._add_new_feature_names(self.feature_names_in_)
return self

def transform(self, X: pd.DataFrame) -> pd.DataFrame:
Expand All @@ -278,16 +279,23 @@ def transform(self, X: pd.DataFrame) -> pd.DataFrame:
# check if dataset contains na
_check_contains_na(X, self.variables_)

dummies = []
for feature in self.variables_:
for category in self.encoder_dict_[feature]:
dummy_df = pd.DataFrame(
{f"{feature}_{category}": np.where(X[feature] == category, 1, 0)},
index=X.index,
)
X = pd.concat([X, dummy_df], axis=1)
dummies.append(dummy_df)

# drop the original non-encoded variables.
X.drop(labels=self.variables_, axis=1, inplace=True)
non_encoded = [c for c in X.columns if c not in self.variables_]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A collision with a column that isn't encoded still gives duplicates: with a categorical (x, y) and a numeric a_x, the result has columns ['a_x', 'a_x', 'a_y'], same as main. Should that raise?

@Aadrit555 Aadrit555 Nov 26, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing out the retained-column edge case!

You're right: when a non-encoded column (like numeric a_x) is retained and categorical a also emits dummy a_x, the resulting output contains duplicate column names. Consistent with Feature-engine conventions (dataframe_checks.py rejecting duplicated columns to prevent downstream indexing ambiguities), this now raises an informative ValueError explicitly identifying the colliding feature name(s).

The collision validation is evaluated against the final emitted schema (after drop_last and category selection have run), so:

  1. The original OneHotEncoder loses a dummy name when it matches an encoded input column #1106 case (where input a_b is encoded and removed, freeing a_b for the dummy indicator) remains fully supported.
  2. If drop_last=True drops the colliding category, no collision occurs and transformation succeeds normally.
  3. Collisions with retained unencoded columns or between multiple generated dummy features are caught at fit time and fail fast.

I've pushed an update with this validation, asserted exact output values on the original #1106 tests across both variable orders, and added regression tests for the collision cases.

Regarding CI: the py39 failure is pre-existing on main (52 _SklearnCheckInputWrapper failures), and the py310 failure is an upstream pytest 9.2.0 / pluggy 1.7.0 NodeId._str_cache issue. The remaining 7 test matrix suites (py311 through py314, pandas 2.3/3.0, scikit-learn 1.5–1.7), docs, types, and style checks are all green.

if dummies:
X = pd.concat([X[non_encoded], *dummies], axis=1)
else:
X = X[non_encoded]

if not X.columns.is_unique:
self._check_unique_feature_names(X.columns.tolist())

return X

Expand All @@ -306,9 +314,25 @@ def _get_new_features_name(self) -> List:

return feature_names

def _check_unique_feature_names(self, feature_names: List) -> List:
seen = set()
duplicates = []
for f in feature_names:
if f in seen:
duplicates.append(f)
else:
seen.add(f)
if duplicates:
raise ValueError(
f"The resulting transformed dataframe will contain duplicated "
f"variable names: {list(dict.fromkeys(duplicates))}."
)
return feature_names

def _add_new_feature_names(self, feature_names) -> List:
"""Adds new features to df columns, and removes categoricals."""
feature_names = feature_names + self._get_new_features_name()
feature_names = [f for f in feature_names if f not in self.variables_]
feature_names = feature_names + self._get_new_features_name()
self._check_unique_feature_names(feature_names)

return feature_names
69 changes: 69 additions & 0 deletions tests/test_encoding/test_onehot_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,3 +534,72 @@ def test_inverse_transform_raises_not_implemented_error(df_enc_binary):
enc = OneHotEncoder().fit(df_enc_binary)
with pytest.raises(NotImplementedError):
enc.inverse_transform(df_enc_binary)


def test_onehot_encoder_dummy_name_matches_input_column():
X = pd.DataFrame({"a_b": ["x", "x", "y", "y"], "a": ["b", "c", "b", "c"]})

# 1. Default order
encoder = OneHotEncoder()
result = encoder.fit_transform(X)
expected_cols = ["a_b_x", "a_b_y", "a_b", "a_c"]
expected_values = [
[1, 0, 1, 0],
[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 1, 0, 1],
]
assert result.columns.tolist() == expected_cols
assert result.values.tolist() == expected_values
assert list(encoder.get_feature_names_out()) == expected_cols

# set_output pandas check
res_pandas = encoder.set_output(transform="pandas").transform(X)
assert res_pandas.columns.tolist() == expected_cols
assert res_pandas.values.tolist() == expected_values

# 2. Reverse variable order
encoder_rev = OneHotEncoder(variables=["a", "a_b"])
result_rev = encoder_rev.fit_transform(X)
expected_rev_cols = ["a_b", "a_c", "a_b_x", "a_b_y"]
expected_rev_values = [
[1, 0, 1, 0],
[0, 1, 1, 0],
[1, 0, 0, 1],
[0, 1, 0, 1],
]
assert result_rev.columns.tolist() == expected_rev_cols
assert result_rev.values.tolist() == expected_rev_values
assert list(encoder_rev.get_feature_names_out()) == expected_rev_cols


def test_onehot_encoder_raises_error_on_output_feature_name_collision():
# 1. Collision with retained non-encoded numeric column
X = pd.DataFrame({"a": ["x", "y"], "a_x": [10, 20]})
encoder = OneHotEncoder()

msg = (
"The resulting transformed dataframe will contain duplicated "
"variable names: ['a_x']."
)
with pytest.raises(ValueError) as excinfo:
encoder.fit(X)
assert str(excinfo.value) == msg

with pytest.raises(ValueError) as excinfo:
encoder.fit_transform(X)
assert str(excinfo.value) == msg

# 2. When drop_last=True drops the colliding category, no collision occurs
X_drop = pd.DataFrame({"a": ["y", "x"], "a_x": [10, 20]})
encoder_drop = OneHotEncoder(drop_last=True)
res_drop = encoder_drop.fit_transform(X_drop)
assert res_drop.columns.tolist() == ["a_x", "a_y"]
assert list(encoder_drop.get_feature_names_out()) == ["a_x", "a_y"]

# 3. Collision between two generated dummy features
X_dupe_dummies = pd.DataFrame({"a_b": ["c", "d"], "a": ["b_c", "e"]})
encoder_dupe = OneHotEncoder()
with pytest.raises(ValueError) as excinfo:
encoder_dupe.fit(X_dupe_dummies)
assert "a_b_c" in str(excinfo.value)