Ordinal Encoder with Explicit Ordering

Quick Overview

Implement a pandas ordinal encoder that maps each category to its position in a user-supplied ordering and sends unseen or missing values to a fallback code. It tests input validation, NaN handling, output dtype rules, and keeping the DataFrame index and column order intact.

Ordinal Encoder with Explicit Ordering

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `OrdinalEncoder(categories, unknown_value=-1)`, where `categories` is a dict mapping a column name to an ordered list. Each category encodes to its position in that list. Unseen or missing values (`None`, `NaN`) encode to `unknown_value`. The encoder must meet these requirements: - `__init__` raises `ValueError` when `categories` is not a dict or when an ordering contains a duplicate. - `fit` stores `mapping_` (for example `{"size": {"low": 0, ...}}`) and returns `self`. A listed column absent from `X` raises `ValueError`. - `transform` before `fit` raises `RuntimeError`. A missing column raises `ValueError`. - `transform` returns a new DataFrame. Encoded columns are `int64` if `unknown_value` is an int (not a bool), else `float64`. - Other columns, column order and index are preserved. The input is not mutated. Example: ```python enc = OrdinalEncoder({"size": ["low", "medium", "high"]}) enc.fit(train_df) enc.transform(pd.DataFrame({"size": ["high", "huge", None]})) # size: [2, -1, -1] (dtype int64) ``` ```hint Two pitfalls Before any dictionary lookup, think about how a missing value compares with itself (`NaN == NaN`). Before choosing the output dtype, check what `isinstance(True, int)` returns. ``` ### What a Strong Answer Covers - The validation in `__init__`, `fit` and `transform`, with the exception type each requirement names. - How missing values and unseen categories are detected and sent to `unknown_value`. - How the output dtype is chosen, including the case of a boolean `unknown_value`. - How the result keeps the index, column order and untouched columns without mutating the input. - The cost of `transform` and the edge cases that a vectorized version would have to match. ### Follow-up Questions - How would you raise an error on unseen categories instead of encoding them? - How would you add `inverse_transform`, and what should it return for `unknown_value`? - When is ordinal encoding a poor fit compared with one-hot encoding, and which model families tolerate it? - How would you vectorize `transform` for a column with tens of millions of rows?

Overview: Implement a pandas ordinal encoder that maps each category to its position in a user-supplied ordering and sends unseen or missing values to a fallback code. It tests input validation, NaN handling, output dtype rules, and keeping the DataFrame index and column order intact.

PracHub logo
General
Nov 25, 2026
easyMachine Learning EngineerOtherMachine Learning
0
0

Implement OrdinalEncoder(categories, unknown_value=-1), where categories is a dict mapping a column name to an ordered list. Each category encodes to its position in that list. Unseen or missing values (None, NaN) encode to unknown_value.

The encoder must meet these requirements:

  • __init__ raises ValueError when categories is not a dict or when an ordering contains a duplicate.
  • fit stores mapping_ (for example {"size": {"low": 0, ...}} ) and returns self . A listed column absent from X raises ValueError .
  • transform before fit raises RuntimeError . A missing column raises ValueError .
  • transform returns a new DataFrame. Encoded columns are int64 if unknown_value is an int (not a bool), else float64 .
  • Other columns, column order and index are preserved. The input is not mutated.

Example:

enc = OrdinalEncoder({"size": ["low", "medium", "high"]})
enc.fit(train_df)
enc.transform(pd.DataFrame({"size": ["high", "huge", None]}))
# size: [2, -1, -1]  (dtype int64)

What a Strong Answer Covers Guidance

  • The validation in __init__ , fit and transform , with the exception type each requirement names.
  • How missing values and unseen categories are detected and sent to unknown_value .
  • How the output dtype is chosen, including the case of a boolean unknown_value .
  • How the result keeps the index, column order and untouched columns without mutating the input.
  • The cost of transform and the edge cases that a vectorized version would have to match.

Follow-up Questions Guidance

  • How would you raise an error on unseen categories instead of encoding them?
  • How would you add inverse_transform , and what should it return for unknown_value ?
  • When is ordinal encoding a poor fit compared with one-hot encoding, and which model families tolerate it?
  • How would you vectorize transform for a column with tens of millions of rows?