Repository navigation
Conversation
… 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
left a comment
There was a problem hiding this comment.
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_] |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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:
- The original OneHotEncoder loses a dummy name when it matches an encoded input column #1106 case (where input
a_bis encoded and removed, freeinga_bfor the dummy indicator) remains fully supported. - If
drop_last=Truedrops the colliding category, no collision occurs and transformation succeeds normally. - Collisions with retained unencoded columns or between multiple generated dummy features are caught at
fittime 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.
7374bc2 to
ac2b006
Compare
Summary of Changes
Fixes #1106
Problem
OneHotEncodergenerates a dummy feature whose name matches another input column being encoded (e.g. input columnsa_banda, whereahas category"b", producing dummy"a_b"):transform(), dummy columns were previously concatenated directly ontoXinside the loop before droppingself.variables_. If"a"was processed before"a_b",Xacquired duplicate"a_b"columns, causingX[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 subsequentX.drop(labels=self.variables_, axis=1)dropped both original"a_b"and dummy"a_b"._add_new_feature_names(), new feature names were appended tofeature_namesand 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 inself.variables_, causingget_feature_names_out()to omit the dummy column and breakingset_output(transform="pandas").a_x) is retained while categoricalaemits dummya_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
transform(), collect all generated dummy DataFrames in a separate listdummies = []during iteration without mutatingX. Retain unencoded columns withnon_encoded = [c for c in X.columns if c not in self.variables_]and concatenate once:pd.concat([X[non_encoded], *dummies], axis=1)._add_new_feature_names(), filterself.variables_fromfeature_namesBEFORE appendingself._get_new_features_name()._check_unique_feature_names():drop_last, category selection, and unencoded retention).ValueErrornaming the colliding feature(s) if duplicate column names would be produced in the output.fit()time to fail fast and keepfit(),transform(),get_feature_names_out(), andset_output(transform="pandas")consistent.Testing & CI
test_onehot_encoder_dummy_name_matches_input_column: verifies default column ordering, reversed variable ordering, exact output values,get_feature_names_out(), andset_output(transform="pandas").test_onehot_encoder_raises_error_on_output_feature_name_collision: verifiesValueErroron retained unencoded column collision, ensuresdrop_last=Truesucceeds when dropping the colliding category, and catches dummy-dummy collisions.tests/test_encoding/test_onehot_encoder.pypass. Formatted and linted cleanly withblack.main(52_SklearnCheckInputWrapperfailures), and py310 is an upstream pytest 9.2.0 / pluggy 1.7.0NodeId._str_cacheinternal error. All 10 other jobs (py311-py314, pandas 2.3/3.0, scikit-learn 1.5-1.7, docs, style, type) passed.