Categorical encoding
Quick answer
Categorical encoding converts labels such as shipping method into numerical features. One-hot encoding creates one indicator per learned category: for the vocabulary air, road, a road shipment becomes [0, 1]. Nominal categories have no inherent order, so arbitrary integers may suggest a false ordering to a model. All examples use synthetic inputs and local scikit-learn 1.8.0 where imported; ByteMind package execution is unverified.
Fit a frozen vocabulary
Fit on road, air and road; transform one known and one new shipping method.
from sklearn.preprocessing import OneHotEncoderenc = OneHotEncoder(handle_unknown='ignore', sparse_output=False)enc.fit([['road'], ['air'], ['road']])print(enc.categories_[0].tolist())print(enc.transform([['road'], ['rail']]).astype(int).tolist())Expected output:
['air', 'road'][[0, 1], [0, 0]]The learned string vocabulary is sorted; rail does not create a new column.
How it works
An ordinal feature has a meaningful rank (small, medium, large), but adjacent ranks need not have equal physical differences. OrdinalEncoder with an explicit category order can represent ranks; one-hot encoding avoids imposing such order for nominal features. Learn vocabulary only from training data, preserve column order and decide how missing and unfamiliar categories differ. With OneHotEncoder(handle_unknown="ignore", drop=None), an unfamiliar value maps to all zeros for that feature. This is a fallback representation, not evidence of a known category. With dropped categories an unknown value may share the same representation as the dropped reference level. A separate unknown flag or reserved bucket can be useful. High-cardinality fields may generate many features; measure memory and consider grouping only using training counts. Target encoding requires out-of-fold training encodings to avoid label leakage; it is not a shortcut here.
Set an explicit ordinal order
Use a declared size order rather than alphabetic order. Unknown levels receive -1 under this particular contract.
from sklearn.preprocessing import OrdinalEncoderenc = OrdinalEncoder(categories=[['small','medium','large']], handle_unknown='use_encoded_value', unknown_value=-1)enc.fit([['large'], ['small'], ['medium']])print(enc.transform([['medium'], ['large'], ['tiny']]).astype(int).ravel().tolist())Expected output:
[1, 2, -1]Medium is rank 1 and large rank 2. The sentinel -1 does not mean physically smaller; downstream handling needs care.
Common mistakes
Do not call get_dummies separately on train and test without reconciling the schema. Do not encode city names as numbers and interpret their distances. Unknown categories and missing categories are different unless a deliberate policy merges them. Monitor unknown rates and maintain feature-name order in model metadata.
Practice and recap
Try encode with a fixed vocabulary. Input [vocabulary, values] with a unique list of strings in the required output order and a list of strings. Return a row of 0/1 indicators per value; unknown values produce all zeros. Empty vocabulary gives an empty row per value. Do not sort or expand the vocabulary. Then explain the preprocessing assumptions before choosing a transformation. Next: Scaling and constant columns.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Categorical encoding — knowledge check
Apply the preprocessing concept to small synthetic data and diagnose mistakes.
Which representation avoids imposing order on shipping methods?
Vocabulary is [road, air]. What is air?
What does an unknown category become with drop=None and handle_unknown="ignore"?
When should a vocabulary be learned?
Why can dropped categories complicate unknown handling?