Skip to content

[BUG] Fix OneHotEncoder losing dummy column when name matches encoded column (#1106) - #1137

Open
Aadrit555 wants to merge 2 commits into
feature-engine:mainfrom
Aadrit555:fix/1106-onehotencoder-dummy-name-clash
Open

Aadrit555 wants to merge 2 commits into
feature-engine:mainfrom
Aadrit555:fix/1106-onehotencoder-dummy-name-clash

Conversation

@Aadrit555

@Aadrit555 Aadrit555 commented Nov 23, 2026 •

Copy link
Copy Markdown

Summary of Changes

Fixes #1106

Problem

  1. When OneHotEncoder generates a dummy feature whose name matches another input column being encoded (e.g. input columns a_b and a, where a has category "b", producing dummy "a_b"):
    • In transform(), dummy columns were previously concatenated directly onto X inside the loop before dropping self.variables_. If "a" was processed before "a_b", X acquired duplicate "a_b" columns, causing X[feature] to extract a 2D DataFrame in the next iteration and raising:
      ValueError: Data must be 1-dimensional, got ndarray of shape (4, 2) instead.
      If "a_b" was processed before "a", the subsequent X.drop(labels=self.variables_, axis=1) dropped both original "a_b" and dummy "a_b".
    • In _add_new_feature_names(), new feature names were appended to feature_names and then filtered with [f for f in feature_names if f not in self.variables_]. This stripped the newly generated dummy feature "a_b" because its name was in self.variables_, causing get_feature_names_out() to omit the dummy column and breaking set_output(transform="pandas").
  2. As noted in review, when a non-encoded column (e.g. numeric a_x) is retained while categorical a emits dummy a_x, the transformed DataFrame produced duplicate column names ['a_x', 'a_x', 'a_y'], which is ambiguous and breaks downstream pipelines and column lookups.

Solution

  1. In transform(), collect all generated dummy DataFrames in a separate list dummies = [] during iteration without mutating X. Retain unencoded columns with non_encoded = [c for c in X.columns if c not in self.variables_] and concatenate once: pd.concat([X[non_encoded], *dummies], axis=1).
  2. In _add_new_feature_names(), filter self.variables_ from feature_names BEFORE appending self._get_new_features_name().
  3. Add final output schema validation via _check_unique_feature_names():
    • Evaluated on the final emitted schema (after drop_last, category selection, and unencoded retention).
    • Raises an informative ValueError naming the colliding feature(s) if duplicate column names would be produced in the output.
    • Run at fit() time to fail fast and keep fit(), transform(), get_feature_names_out(), and set_output(transform="pandas") consistent.

Testing & CI

  • Regression test test_onehot_encoder_dummy_name_matches_input_column: verifies default column ordering, reversed variable ordering, exact output values, get_feature_names_out(), and set_output(transform="pandas").
  • Regression test test_onehot_encoder_raises_error_on_output_feature_name_collision: verifies ValueError on retained unencoded column collision, ensures drop_last=True succeeds when dropping the colliding category, and catches dummy-dummy collisions.
  • All 31 unit tests in tests/test_encoding/test_onehot_encoder.py pass. Formatted and linted cleanly with black.
  • Note on CircleCI: The py39 failure is pre-existing on upstream main (52 _SklearnCheckInputWrapper failures), and py310 is an upstream pytest 9.2.0 / pluggy 1.7.0 NodeId._str_cache internal error. All 10 other jobs (py311-py314, pandas 2.3/3.0, scikit-learn 1.5-1.7, docs, style, type) passed.

… column

In OneHotEncoder.transform, collect dummies separately before dropping encoded variables to prevent column collisions during iteration and accidental dropping of dummy columns. In _add_new_feature_names, remove encoded variables before appending new feature names.

Fixes feature-engine#1106

@atishay-kasliwal atishay-kasliwal left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ran the collision cases on main and here. Two encoded columns colliding works now.


# 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.

Validate that final emitted feature names are unique, raising ValueError if a generated dummy collides with an unencoded retained column or another dummy. Run validation at fit time to fail fast and guard transform against duplicate columns. Add regression tests asserting output values for issue feature-engine#1106 and covering collision edge cases.
@Aadrit555
Aadrit555 force-pushed the fix/1106-onehotencoder-dummy-name-clash branch from 7374bc2 to ac2b006 Compare November 26, 2026 01:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OneHotEncoder loses a dummy name when it matches an encoded input column

2 participants