---
title: One-hot encoding with an unknown bucket
url: https://gurkanozkan.ai/learn/coding/mle-one-hot-encoding-with-an-unknown-bucket-07/
markdown: https://gurkanozkan.ai/learn/coding/mle-one-hot-encoding-with-an-unknown-bucket-07.md
kind: coding
difficulty: Warm-up
topics:
  - Preprocessing
  - Categorical
  - Data quality
json: https://gurkanozkan.ai/api/learn/coding/mle-one-hot-encoding-with-an-unknown-bucket-07.json
robots: noindex
---

# One-hot encoding with an unknown bucket

Build the vocabulary as the sorted unique values of `train_col` followed by `"<unk>"`. Return `(vocab, rows)`, where `rows` one-hot encodes each value of `test_col` and maps unseen values to the `"<unk>"` column.

## Signature

```python
def one_hot(train_col: list[str], test_col: list[str]) -> tuple[list[str], list[list[int]]]: ...
```

## Examples

Each call and the value it should give.

```python
>>> one_hot(['b','a','b'], ['a','b']) == (['a', 'b', '<unk>'], [[1, 0, 0], [0, 1, 0]])
True

>>> one_hot(['b','a'], ['z']) == (['a', 'b', '<unk>'], [[0, 0, 1]])
True
```

## Hints

1. Vocabulary: sorted unique train values followed by <unk>.
2. Dict lookup with a default — unseen values map to <unk>.
3. Return (vocab, rows) where rows are one-hot aligned to that vocab.

## Reference solution

```python
def one_hot(train_col, test_col):
    vocab = sorted(set(train_col)) + ["<unk>"]
    idx = {c: i for i, c in enumerate(vocab[:-1])}
    rows = []
    for c in test_col:
        r = [0] * len(vocab)
        r[idx.get(c, len(vocab) - 1)] = 1
        rows.append(r)
    return vocab, rows
```

## What a strong solution covers

- Deterministic vocabulary order.
- Dict lookup with a default.
- Discusses rare-category bucketing, hashing for high cardinality, and serving-time consistency.

## Common mistakes

- building the vocabulary from test data
- crashing on unseen categories.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
