One-Hot Encoder with Rare Category Grouping

Quick Overview

Implement a pandas one-hot encoder that keeps the frequent categories learned in fit and sends rare and unseen values to one infrequent column per feature. It tests frequency thresholds, a top-k category cap with a tie rule, missing-value handling and an output schema that stays fixed after fitting.

One-Hot Encoder with Rare Category Grouping

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `RareCategoryOneHotEncoder` with `fit`, `transform`, `fit_transform` and `get_feature_names_out` on a pandas DataFrame. Each encoded column keeps the frequent categories learned in `fit` and maps all other values to a single infrequent column, so output columns never change after fitting. The constructor is `RareCategoryOneHotEncoder(columns=None, min_frequency=None, max_categories=None, infrequent_label="infrequent")`, and the encoder must meet these requirements: - Encode `columns` in the given order (all columns if `None`). Store kept categories in `categories_` as `{col: [cats sorted by str]}`. - Keep categories with count ≥ `min_frequency` (int: absolute count, float: fraction of non-missing rows, `None`: every observed category). Then, if `max_categories` is set, keep the top-k by count (ties: `str` ascending). - Return an `int64` DataFrame with the input index and columns `{col}_{cat}` per kept category followed by `{col}_{infrequent_label}`. `get_feature_names_out()` returns these names as a list. - Rare or unseen values get a 1 in the infrequent column. Missing values (`None`/`NaN`) get all zeros and are excluded from counts. - Never mutate the input. Calling `transform` or `get_feature_names_out` before `fit` raises `RuntimeError`. For example, with `min_frequency=2` only `red` (3 rows) and `blue` (2 rows) are kept, and `green` goes to the infrequent column: ```python X = pd.DataFrame({"color": ["red", "blue", "red", "green", "blue", "red"]}) enc = RareCategoryOneHotEncoder(min_frequency=2) enc.fit_transform(X) # color_blue color_red color_infrequent # 0 0 1 0 # 1 1 0 0 # 2 0 1 0 # 3 0 0 1 # 4 1 0 0 # 5 0 1 0 enc.categories_ # {"color": ["blue", "red"]} ``` ```hint Freeze the layout in fit Everything `transform` writes (which categories survive, the column names and their order) should come from `fit`. Check that nothing in `transform` counts values in the frame it is given. ``` ```hint Missing is not rare Missing values and rare values both fail to match a kept category, but they end up in different places. Keep them apart in the counts and in the infrequent column. ``` ### What a Strong Answer Covers - How `fit` picks the kept categories: the integer and fractional forms of `min_frequency` (including a count that lands exactly on the threshold), then the `max_categories` cut and its tie rule. - A column layout fixed at fit time that `transform` and `get_feature_names_out` both reuse. - How rare, unseen and missing values are routed in `transform`, and how missing values affect the fractional threshold. - The interface details: `int64` output, the input index preserved, no mutation, `RuntimeError` before `fit`. - The cost of `transform` and edge cases such as an all-missing column or a category name that collides with the infrequent label. ### Follow-up Questions - How would you return sparse output for high-cardinality columns? - How would you add a `drop` option to avoid perfect collinearity for linear models, given that each feature has an infrequent column? - Should missing values get their own indicator column?

Overview: Implement a pandas one-hot encoder that keeps the frequent categories learned in fit and sends rare and unseen values to one infrequent column per feature. It tests frequency thresholds, a top-k category cap with a tie rule, missing-value handling and an output schema that stays fixed after fitting.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement RareCategoryOneHotEncoder with fit, transform, fit_transform and get_feature_names_out on a pandas DataFrame. Each encoded column keeps the frequent categories learned in fit and maps all other values to a single infrequent column, so output columns never change after fitting.

The constructor is RareCategoryOneHotEncoder(columns=None, min_frequency=None, max_categories=None, infrequent_label="infrequent"), and the encoder must meet these requirements:

  • Encode columns in the given order (all columns if None ). Store kept categories in categories_ as {col: [cats sorted by str]} .
  • Keep categories with count ≥ min_frequency (int: absolute count, float: fraction of non-missing rows, None : every observed category). Then, if max_categories is set, keep the top-k by count (ties: str ascending).
  • Return an int64 DataFrame with the input index and columns {col}_{cat} per kept category followed by {col}_{infrequent_label} . get_feature_names_out() returns these names as a list.
  • Rare or unseen values get a 1 in the infrequent column. Missing values ( None / NaN ) get all zeros and are excluded from counts.
  • Never mutate the input. Calling transform or get_feature_names_out before fit raises RuntimeError .

For example, with min_frequency=2 only red (3 rows) and blue (2 rows) are kept, and green goes to the infrequent column:

X = pd.DataFrame({"color": ["red", "blue", "red", "green", "blue", "red"]})
enc = RareCategoryOneHotEncoder(min_frequency=2)
enc.fit_transform(X)
#    color_blue  color_red  color_infrequent
# 0           0          1                 0
# 1           1          0                 0
# 2           0          1                 0
# 3           0          0                 1
# 4           1          0                 0
# 5           0          1                 0
enc.categories_  # {"color": ["blue", "red"]}

What a Strong Answer Covers Guidance

  • How fit picks the kept categories: the integer and fractional forms of min_frequency (including a count that lands exactly on the threshold), then the max_categories cut and its tie rule.
  • A column layout fixed at fit time that transform and get_feature_names_out both reuse.
  • How rare, unseen and missing values are routed in transform , and how missing values affect the fractional threshold.
  • The interface details: int64 output, the input index preserved, no mutation, RuntimeError before fit .
  • The cost of transform and edge cases such as an all-missing column or a category name that collides with the infrequent label.

Follow-up Questions Guidance

  • How would you return sparse output for high-cardinality columns?
  • How would you add a drop option to avoid perfect collinearity for linear models, given that each feature has an infrequent column?
  • Should missing values get their own indicator column?