One-Hot Encoder With Unseen Categories
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `OneHotEncoder` with `fit`, `transform`, `fit_transform` and `get_feature_names_out` over a pandas DataFrame. Learn categories in `fit` only, and return a new DataFrame of passthrough columns followed by `int64` indicator columns.
The constructor is `OneHotEncoder(columns=None, drop_first=False, handle_unknown="ignore")`, and the encoder must meet these requirements:
- `columns=None` encodes every column. Store `categories_` as `{col: sorted non-null values}` (missing values are not a category). A listed column absent from `X` raises `KeyError`.
- Output columns are the unencoded columns (original order) first, then `f"{col}_{value}"` per encoded column (in `columns` order, categories sorted). Preserve the index and don't mutate the input.
- `drop_first=True` drops the first sorted category of each column (a single-category column yields no columns).
- Unseen or missing values give an all-zero row in that column's indicators. With `handle_unknown="error"`, unseen non-null values raise `ValueError` (missing values still don't).
- A `handle_unknown` value outside `{"ignore", "error"}` raises `ValueError` in `fit`. Calling `transform` or `get_feature_names_out` before `fit` raises `RuntimeError`.
For example, `purple` was never seen in training and the second row is missing, so both get zeros:
```python
train = pd.DataFrame({"color": ["red", "green", "blue"], "price": [1.5, 2.0, 3.25]})
enc = OneHotEncoder(columns=["color"]).fit(train)
enc.transform(pd.DataFrame({"color": ["purple", None, "red"], "price": [1.0, 2.0, 3.0]}))
# price color_blue color_green color_red
# 0 1.0 0 0 0
# 1 2.0 0 0 0
# 2 3.0 0 0 1
```
```hint Where the schema comes from
Decide every output column in `fit`. Then ask how comparing a value against a fixed list of categories treats a value the list has never seen, and whether that needs any special-case code.
```
### What a Strong Answer Covers
- How `fit` builds and stores each vocabulary, including missing values and the `KeyError` and `handle_unknown` checks.
- The output column order and how `drop_first` changes it.
- How unseen and missing values behave in each `handle_unknown` mode.
- Index preservation, no mutation of the input, `int64` indicators and the `RuntimeError` before `fit`.
### Follow-up Questions
- How would you handle high-cardinality columns with thousands of categories?
- Why does `drop_first` matter, and when should you avoid it?
Overview: Implement a one-hot encoder for pandas DataFrames that learns categories only in fit and places passthrough columns ahead of int64 indicator columns. It tests handling of unseen and missing values, a drop_first option, strict and lenient unknown-category modes, and leaving the input and its index untouched.