Target Encoding for High-Cardinality Features

~15 mincode completion

Implement target_encode(categories, targets) that returns a float array of the same length.

Examples

Three categories: A and B have equal means, C differs

Input
target_encode(["A", "B", "A", "C"], [2, 4, 6, 8])
Output
[4, 4, 4, 8]

X appears twice, mean computed over both occurrences

Input
target_encode(["X", "X", "Y"], [10, 20, 5])
Output
[15, 15, 5]

All unique categories: each maps to its own target value

Input
target_encode(["A", "B", "C"], [1, 2, 3])
Output
[1, 2, 3]

Hints

Hint 1

does the sum and the division in one step.

Hint 2

Reach for target mean rather than label encoding.

Requirements

  • categories: 1D array of category labels (strings), shape (n,)

  • targets: 1D array of numeric target values, shape (n,)

  • Return Float array of shape (n,) with categories replaced by target means.

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~15 min

8 employers weight this skill

3 big tech firms, 2 AI product companies, 1 defense company, 1 enterprise vendor, 1 quant fund. Top match scores 87.

Python
import numpy as np

def target_encode(categories: np.ndarray, targets: np.ndarray) -> np.ndarray:
    """
    Replace each category with the mean of the target for that category.

    Args:
        categories: 1D array of category labels (strings), shape (n,)
        targets:    1D array of numeric target values, shape (n,)

    Returns:
        Float array of shape (n,) with categories replaced by target means.
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.