Sub topic 4
Numeric and Categorical Features
This chapter assumes you can read basic Python and pandas, know what a feature matrix X is, and know that estimators expect arrays of numbers. It covers how to tell numeric columns from categorical ones, why scikit-learn estimators need the difference made explicit, and how to encode each kind safely.
Two kinds of columns
A feature is a column of X. Most columns fall into one of two groups.
- Numeric features hold quantities where arithmetic is meaningful: age, income, temperature, number of purchases. They can be continuous (
3.7) or discrete counts (4). - Categorical features hold labels from a limited set: city, product type, browser name. Arithmetic on them has no meaning, because "Paris + Rome" is not a value.
Categorical features split further, and the split decides which encoder to use.
| Kind | Meaning | Example | Typical encoder |
|---|---|---|---|
| Nominal | Categories with no order | city, color | `OneHotEncoder` |
| Ordinal | Categories with a natural order | small, medium, large | `OrdinalEncoder` with explicit order |
| Binary | Exactly two values | yes, no | `OneHotEncoder(drop="if_binary")` or a 0/1 column |
The column's pandas dtype only hints at its kind. You decide the kind from what the values mean.
Why estimators care
Scikit-learn estimators work on numeric arrays. Passing raw strings fails when the estimator tries to convert them to floats.
from sklearn.linear_model import LogisticRegression
X = [["Paris"], ["Rome"], ["Paris"]]
y = [0, 1, 0]
try:
LogisticRegression().fit(X, y)
except ValueError as e:
print("ValueError:", e)The error is useful. It means a categorical column reached an estimator with no encoding step in front of it.
The opposite failure is quieter. Suppose you replace city names with 0, 1, 2. The model now sees numbers and runs without complaint. A linear model will treat Rome (2) as "twice" Paris (1) and Oslo (0) as the smallest, which is an ordering you invented. Encoding is a modeling decision, not just a type conversion.
Detecting column types in pandas
Start by inspecting the dtypes and selecting columns from them.
import pandas as pd
df = pd.DataFrame({
"age": [22, 35, 47, 52],
"income": [32000.0, 54000.5, 61000.0, 48000.0],
"city": ["Paris", "Rome", "Paris", "Oslo"],
"size": ["small", "large", "medium", "small"],
"zip_code": [75001, 100, 75002, 150],
})
print(df.dtypes)
numeric_cols = df.select_dtypes(include="number").columns.tolist()
other_cols = df.select_dtypes(exclude="number").columns.tolist()
print(numeric_cols) # ['age', 'income', 'zip_code']
print(other_cols) # ['city', 'size']zip_code shows the main limit of dtype-based detection. It is stored as an integer, so select_dtypes calls it numeric. But a zip code is an identifier. Subtracting two of them or averaging them is meaningless. Treat it as categorical, either by converting it to strings first or by listing it explicitly in the categorical group.
Common cases where dtype misleads:
- Integer-coded categories (zip codes, product IDs, status codes).
- Numbers stored as strings (
"42"), which show up as non-numeric and may needpd.to_numeric. - Boolean columns, which are neither clearly numeric nor categorical. Treating them as 0/1 numeric is usually fine.
- Dates, which are neither. Extract numeric parts such as year, month, or days since a reference date.
Encoding nominal features with OneHotEncoder
One-hot encoding replaces a categorical column with one 0/1 column per category. A row has a 1 in the column matching its category and 0 elsewhere. No order is implied, because each category gets its own axis.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"city": ["Paris", "Rome", "Paris", "Oslo"]})
test = pd.DataFrame({"city": ["Rome", "Madrid"]})
enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
enc.fit(train)
print(enc.categories_)
print(enc.get_feature_names_out())
print(enc.transform(test))OneHotEncoder follows the transformer conventions from earlier chapters, and three points matter here.
fitlearns the categories. The learned list is stored incategories_, an attribute ending in an underscore. Categories are sorted alphabetically here: Oslo, Paris, Rome.transformuses only those categories. Madrid never appeared in training, so the encoder has no column for it. Withhandle_unknown="ignore", Madrid becomes a row of all zeros. With the default ("error"),transformraises aValueError.- The output width is fixed at fit time. A test set with fewer or more cities still produces three columns. This is why you fit the encoder on training data and not separately on each split.
pd.get_dummies also produces one-hot columns, but it has no fit step. Run on train and test separately, it can produce different columns for each. Prefer OneHotEncoder inside a pipeline.
Choosing whether to drop a column
The one-hot columns of a feature always sum to 1, so any one of them is predictable from the others. For unregularized linear models this redundancy can cause numerical trouble. drop="first" removes one column per feature, and drop="if_binary" removes one column only for two-category features. Regularized models, which include the default LogisticRegression, and tree-based models do not need this. Dropping also makes unknown-category handling less clean, so treat it as an option and not a default.
Encoding ordinal features with OrdinalEncoder
When the categories have an order, a single integer column can keep that information. The important point is to state the order yourself. Without it, OrdinalEncoder sorts alphabetically, which puts "large" before "medium" before "small".
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
sizes = pd.DataFrame({"size": ["small", "large", "medium", "small"]})
ord_enc = OrdinalEncoder(categories=[["small", "medium", "large"]])
print(ord_enc.fit_transform(sizes).ravel()) # [0. 2. 1. 0.]The categories argument is a list with one inner list per column. The result treats the gaps between levels as equal. If "medium" to "large" is a much bigger step than "small" to "medium", a linear model will not see that. A tree model only uses the order, so it is less affected.
OrdinalEncoder also takes handle_unknown="use_encoded_value" together with unknown_value=-1 (or np.nan) for categories not seen during fit.
Do not use OrdinalEncoder on nominal features with a linear model just to get fewer columns. It reintroduces the fake ordering described earlier. Tree-based models are more forgiving, and some scikit-learn models support categorical features natively, but one-hot encoding is the safe default.
Scaling numeric features
Numeric columns often need rescaling because their units differ. Age spans tens, income spans tens of thousands. Models that depend on distances or on gradient-based optimization (k-nearest neighbors, SVMs, regularized linear models, neural networks) are sensitive to this, because the large-scale column dominates. Decision trees and random forests split on thresholds per feature, so they are largely unaffected.
StandardScaler subtracts the training mean and divides by the training standard deviation. It is a transformer, so the data leakage rule applies: call fit on training data only, then transform on both splits. Do not scale one-hot columns or ordinal codes by habit. Scaled indicator columns lose their simple 0/1 meaning, though the model usually still works.
Handling both kinds together
A real table has both kinds of columns, and each group needs a different transformer. ColumnTransformer routes columns to transformers. A selector lets you choose columns by dtype instead of typing names.
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = pd.DataFrame({
"age": [22, 35, 47, 52],
"income": [32000.0, 54000.5, 61000.0, 48000.0],
"city": ["Paris", "Rome", "Paris", "Oslo"],
"size": ["small", "large", "medium", "small"],
})
pre = ColumnTransformer(
[
("num", StandardScaler(), make_column_selector(dtype_include="number")),
(
"cat",
OneHotEncoder(handle_unknown="ignore"),
make_column_selector(dtype_exclude="number"),
),
],
sparse_threshold=0,
)
out = pre.fit_transform(X)
print(out.shape) # (4, 8)
print(pre.get_feature_names_out())The eight output columns are two scaled numeric ones, three city indicators, and three size indicators. Here size is one-hot encoded as if nominal. If you want it ordinal, add a third entry with OrdinalEncoder and select size by name. The next chapters show how this fits into a Pipeline with a model.
The decision process looks like this.
Edge cases to check
- Missing values. Most estimators reject
NaN. Add aSimpleImputerbefore the scaler or encoder. Use the median for numeric columns and the most frequent value (or a constant such as"missing") for categorical ones. - High cardinality. A column with thousands of categories (user ID, free-text city) creates thousands of one-hot columns. Consider grouping rare categories (
min_frequencyinOneHotEncoder) or dropping the column. - Rare categories in cross-validation. A category can appear in a validation fold but not in the training fold. Use
handle_unknown="ignore"so the fold does not crash. - Column order and names. When you pass a DataFrame,
ColumnTransformerselects by name, so reordering columns is safe. With a NumPy array, selection is by position. - Labels are different. Class labels in
yneed no one-hot encoding. Classifiers accept strings inydirectly. This chapter concerns features inX.
Exercise
A DataFrame has a numeric column customer_id stored as integers. A teammate builds a ColumnTransformer that selects columns with make_column_selector(dtype_include="number") and applies StandardScaler. What is wrong, and how would you fix it?
Show answer
customer_id is an identifier, not a quantity, but its integer dtype puts it in the numeric group, so it gets scaled and the model may read a meaningless ordering or size from it. Fix it by dropping the column if it has no predictive meaning, or by converting it to strings (or selecting columns by name) and routing it to a categorical encoder. With very many distinct IDs, dropping is usually better than one-hot encoding.
Exercise
You fit OneHotEncoder() with default settings on training cities {Oslo, Paris, Rome}. At prediction time a row has the city "Madrid". What happens, and which parameter changes it?
Show answer
transform raises a ValueError because Madrid is an unknown category. Setting handle_unknown="ignore" encodes Madrid as a row of zeros across the city columns, and the prediction goes ahead.
Exercise
Why should OrdinalEncoder for a "size" column be given categories=[["small", "medium", "large"]] instead of relying on the default?
Show answer
By default the encoder sorts categories alphabetically, giving large=0, medium=1, small=2, which reverses the true order. Passing the categories explicitly makes the integer codes match the real order (small=0, medium=1, large=2).