Data & Features ยท Medium
Categorical Encoding
Implement Categorical Encoding with production-minded edge case handling.
Task
Implement categorical_encoding(values: list[int], categories: list[int]) -> list[list[int]]. One-hot encode integer category values using a caller-provided category order, mapping unknown values to all-zero rows.
Requirements
- categories contains unique integer IDs and defines the output column order.
- Return one row per input value and one column per category.
- Set exactly the matching category column to 1 for a known value.
- Encode a value absent from categories as an all-zero row.
- Preserve input row order and do not sort or infer categories.
- Handle empty values or empty categories without mutating either input.
Example
categorical_encoding([20, 10, 99], [10, 20, 30])
# [[0, 1, 0], [1, 0, 0], [0, 0, 0]]