Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

241. Ordinal encoding

easy
GeneralGeneral
senior

Ordinal encoding is a simple way to turn ordered categorical values (like sizes) into numbers so models can use them. You’ll implement an ordinal encoder that maps each category to an integer based on a provided ordering.

Requirements

Implement the function

python

Rules:

  • Use the mapping ( \text{code}(c) = \text{index}(c \text{ in ordered_categories}) ).
  • If a value is not present in ordered_categories, encode it as unknown_value.
  • Return a NumPy array of integers.
  • Do not use any prebuilt encoders (e.g., from scikit-learn).
  • Keep it in a single function.

Example

python

Output:

python
Input Signature
ArgumentType
valuesnp.ndarray
unknown_valueint
ordered_categoriesnp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Return NumPy array

  • No scikit-learn or prebuilt encoders

  • Single function implementation only

Hint 1

Start by thinking: for each value, you need its position in ordered_categories (or a fallback).

Hint 2

Precompute a lookup dict {category: index} using enumerate(ordered_categories) to avoid repeated .index() calls.

Hint 3

Use dict.get(value, unknown_value) inside a list comprehension to produce the final list[int] in one pass.

Roles
ML Engineer
AI Engineer
Data Scientist
Quantitative Analyst
Companies
GeneralGeneral
Levels
senior
entry
Tags
ordinal-encoding
hash-map
categorical-features
python-list-comprehension
34 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit