Ordinal-encode a category column and map unseen values to -1
Why it matters Ordinal codes are the default categorical input for gradient boosted trees, and a stable mapping is needed so a saved model reads new data the same way.
Tree models are happy with categories turned into integer codes, as long as the codes are learned from training data and unknown values get a safe code.
Write ordinal_encode(train, test, unknown=-1). train and test are lists of strings. The vocabulary is the sorted set of distinct train values, and each value gets its position in that sorted list. Return a list of ints, one code per test value, using unknown for values never seen in train.
def ordinal_encode(train, test, unknown=-1)Example
train ["red", "blue", "red", "green"], test ["green", "pink", "blue"] gives [1, -1, 0] (blue 0, green 1, red 2).
Understand the idea
Ordinal encoding gives every category a whole number, like giving each city on a train route a stop number. The numbers must stay the same every time you run the pipeline, so we sort the vocabulary instead of trusting row order.
Worked example: train values red, blue, red, green. The sorted distinct set is blue, green, red, so blue is 0, green is 1 and red is 2. For test values green, pink, blue we output 1, then -1 because pink was never seen, then 0.
Rule: code(v) = position of v in sorted(set(train)) if v was seen, else unknown.
The unknown code matters in production, where a new city or product id will always show up eventually. Gradient boosted tree libraries take ordinal codes directly, and many feature stores keep the saved vocabulary next to the model so that serving and training use identical codes.