Sub topic 12
Encoding categoricals for machine learning
Most machine learning models need numbers, not strings. This chapter shows how to turn pandas categorical columns into numeric features without introducing silent errors. It assumes you can create categoricals with astype("category") or CategoricalDtype, read .cat.codes and .cat.categories, and know how ordered categoricals work. It also assumes you have basic familiarity with NumPy-style arrays and with fitting a model on a feature matrix.
Two ways to encode
A categorical already stores integer codes, so conversion to numbers looks free. There are two common strategies, and they make different claims about your data.
- Integer codes map each category to one integer. This gives one column per feature. It tells the model that the categories are ordered and evenly spaced.
- One-hot encoding creates one 0/1 column per category. It makes no claim about order, but it adds as many columns as there are categories.
The right choice depends on whether the category has a real order and on which model you use.
Integer codes for ordered data
For an ordered categorical, the code is the position in the category order. Because the order is meaningful, the integers carry real information.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
s = pd.Series(["small", "large", "medium", "small"], dtype=size_type)
print(s.cat.codes.tolist()) # [0, 2, 1, 0]
print(s.cat.codes.dtype) # int8The codes follow the order you declared, not alphabetical order. That is why you should set the categories explicitly before encoding. If you had let pandas infer the categories, large would come first and receive code 0.
The codes come back as the smallest integer type that fits, such as int8. Some libraries are happy with that. If a library complains, or if you do arithmetic that could overflow, convert with .astype("int64").
Codes for unordered data
You can also take codes from an unordered categorical. This is a common shortcut for tree-based models such as random forests and gradient boosting. Trees split on thresholds like code <= 2, and with enough splits they can isolate any single category.
For linear models, logistic regression, and neural networks, it is usually a mistake. The model will treat red=2 as twice green=1 and will fit a single slope across them. The alphabetical order that produced those numbers has no meaning.
One-hot encoding with get_dummies
pd.get_dummies expands categorical columns into indicator columns. Pass columns= to choose which ones to expand, and dtype=int to get 0/1 integers. Recent pandas versions return booleans by default.
import pandas as pd
df = pd.DataFrame({
"color": pd.Series(["red", "green", "red", "blue"], dtype="category"),
"price": [10, 12, 9, 15],
})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded)The result has columns price, color_blue, color_green, and color_red. The new columns are named <column>_<category> and appear in category order. Numeric columns such as price pass through unchanged.
Useful options:
drop_first=Trueremoves the first category's column. For a linear model with an intercept, the full set of dummies is perfectly collinear, because the columns always sum to 1. Dropping one avoids that. Regularized models and tree models do not need it.dummy_na=Trueadds a column that flags missing values. Without it, a missing value produces a row of all zeros, which looks the same as an unseen category.prefix=changes the column name prefix when the original column name is long or awkward.
Keeping train and test columns aligned
The most common bug in categorical encoding is a mismatch between the training and test data. If you call get_dummies separately on each, and the two sets contain different values, you get different columns. The model then sees a matrix whose columns mean something different from what it was trained on.
A categorical dtype with fixed categories solves this. get_dummies on a categorical always produces one column per category, including categories that never occur in the data.
import pandas as pd
color_type = pd.CategoricalDtype(["blue", "green", "red"])
train = pd.Series(["red", "green"], dtype=color_type)
test = pd.Series(["blue", "purple"], dtype=color_type)
print(pd.get_dummies(train, dtype=int).columns.tolist())
# ['blue', 'green', 'red']
print(pd.get_dummies(test, dtype=int))
print(test.cat.codes.tolist()) # [0, -1]Both calls return the same three columns. The test set contains purple, which is not in the dtype, so pandas converts it to a missing value when the Series is built. That row is all zeros in the dummies, and its code is -1.
This behavior has two consequences:
- Unseen values are silently turned into
NaN. If you expect new categories in production, count them before you encode, withtest.isna().sum()or by checking the raw values againstcolor_type.categories. - A code of
-1is a valid-looking integer. If you pass it to a model without handling it, the model treats missing values as a category that sits below every real one.
Reusing the training dtype
When you already have a fitted training column, you can reuse its dtype directly:
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "red"]})
test = pd.DataFrame({"color": ["green", "blue"]})
train["color"] = train["color"].astype("category")
test["color"] = test["color"].astype(train["color"].dtype)
print(list(train["color"].cat.categories)) # ['green', 'red']
print(test["color"].tolist()) # ['green', nan]
print(test["color"].cat.codes.tolist()) # [0, -1]The test column inherits the categories green and red. The value blue was not in the training data, so it becomes missing. The codes in both frames now mean the same thing.
Handling missing values
Missing values in a categorical have no category. .cat.codes shows them as -1, and get_dummies shows them as a row of zeros unless you set dummy_na=True.
You have three reasonable options:
- Keep the missingness as information. Use
dummy_na=Truefor one-hot encoding, or add a real category withadd_categories(["unknown"])andfillna("unknown"). - Impute a value, such as the most frequent category, before encoding.
- Let the model handle it. Some tree libraries accept
NaNdirectly.
Option 1 is usually the safest default for categorical features, because "missing" often means something in the data collection process.
Using scikit-learn encoders
When you build a modeling pipeline, scikit-learn's encoders store the learned categories inside the fitted object. That keeps the training and test encoding consistent even when the data arrives later. The example below uses sparse_output, which needs scikit-learn 1.2 or later.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
categories = [["blue", "green", "red"]]
enc = OneHotEncoder(categories=categories, handle_unknown="ignore", sparse_output=False)
train = pd.DataFrame({"color": ["red", "green"]})
test = pd.DataFrame({"color": ["blue", "purple"]})
enc.fit(train)
print(enc.transform(test))
# [[1. 0. 0.]
# [0. 0. 0.]]With handle_unknown="ignore", the unseen value purple becomes a row of zeros instead of raising an error. The default is "error", which stops the pipeline and is the better choice when an unseen category would indicate a data problem.
OrdinalEncoder plays the same role as integer codes. Pass categories= in the order you want, so the numbers follow your logical order rather than alphabetical order.
Pandas categoricals and scikit-learn encoders overlap. A common split is to use pandas dtypes for cleaning and exploration, and a scikit-learn encoder inside the model pipeline so the encoding is saved with the model.
High-cardinality columns
One-hot encoding a column with thousands of categories creates thousands of mostly-zero columns. This is slow and uses a lot of memory, and it can make linear models overfit. Options include:
- Group rare categories into an
"other"category before encoding. Count withvalue_counts()and replace categories below a threshold. - Use integer codes with a tree-based model.
- Use a target-based or hashing encoder from a dedicated library, taking care to fit the target-based encoding only on training data.
import pandas as pd
s = pd.Series(["a"] * 50 + ["b"] * 40 + ["c"] * 2 + ["d"], dtype="category")
counts = s.value_counts()
rare = counts[counts < 5].index
s = s.cat.add_categories(["other"])
s = s.where(~s.isin(rare), "other")
s = s.cat.remove_unused_categories()
print(list(s.cat.categories)) # ['a', 'b', 'other']The order matters here. Adding "other" first makes the assignment valid, and remove_unused_categories cleans up the rare categories afterward.
Summary of common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Encoding train and test separately with `astype("category")` | Different codes or columns | Share one `CategoricalDtype` |
| Unordered codes in a linear model | False numeric scale | One-hot encode |
| Ignoring `-1` codes | Missing values look like a real low category | Fill or flag them first |
| Full dummies with an unregularized linear model | Collinear columns | `drop_first=True` |
| One-hot on thousands of categories | Wide, sparse matrix | Group rare values or use codes |
Exercise
A training column has the categories "low", "mid", and "high" (ordered in that way). The test data contains the value "very high". You build the test column with the training dtype and then call .cat.codes. What code does the "very high" row get, and why is that a problem for a model?
Show answer
It gets -1, because "very high" is not one of the dtype's categories and is converted to a missing value. A model would read -1 as a real number below "low", so it would treat a very high value as the lowest one. Count or handle the missing values before encoding, for example by adding an explicit category or by raising an error when unseen values appear.
Exercise
You call pd.get_dummies(df, columns=["color"]) on a training frame and again on a test frame. The test frame has no "green" rows. What goes wrong if "color" is a plain object column, and how does a categorical dtype prevent it?
Show answer
With an object column, getdummies only creates columns for values present, so the test frame lacks a colorgreen column and its columns no longer line up with the training matrix. With a categorical column that uses the same CategoricalDtype, get_dummies creates one column for every category, including unused ones, so the columns match.