Sub topic 4
Numeric and categorical features
This chapter assumes you can read pandas DataFrames and NumPy arrays, and that you know X holds features and y holds labels. It covers the two kinds of feature columns you will meet most often and why scikit-learn treats them differently.
Two kinds of columns
A numeric feature is a column where the values are quantities and arithmetic on them means something. Age, price, and temperature are examples. A categorical feature is a column where the values are labels from a fixed set, such as city names or product types.
Most scikit-learn estimators accept only numbers. A string column in X raises an error when you call fit. Categorical columns therefore have to be converted to numbers first, and numeric columns often need rescaling.
Finding the types in a DataFrame
pandas records a dtype for each column. You can use it to split the columns into the two groups.
import pandas as pd
df = pd.DataFrame({
"age": [22, 35, 47, 52],
"income": [28000.0, 41000.0, 56000.0, 62000.0],
"city": ["Paris", "Rome", "Paris", "Oslo"],
})
print(df.dtypes)
numeric_cols = df.select_dtypes(include="number").columns.tolist()
categorical_cols = df.select_dtypes(exclude="number").columns.tolist()
print(numeric_cols) # ['age', 'income']
print(categorical_cols) # ['city']The dtype is only a hint. A postal code stored as an integer is categorical, because adding two postal codes or calling one "larger" has no meaning. A column of strings like "42" may be numeric. Decide from what the values mean, then fix the dtype if it disagrees.
Why not just number the categories?
Mapping Paris to 0, Rome to 1, and Oslo to 2 is tempting. A linear model would then treat Rome as halfway between Paris and Oslo, and that relationship does not exist in the data. For unordered (nominal) categories, one-hot encoding is the usual fix. It creates one 0/1 column per category.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
cities = pd.DataFrame({"city": ["Paris", "Rome", "Paris", "Oslo"]})
encoder = OneHotEncoder(sparse_output=False)
encoded = encoder.fit_transform(cities)
print(encoder.categories_) # [array(['Oslo', 'Paris', 'Rome'], dtype=object)]
print(encoded)The output has three columns, in the sorted order of categories_: Oslo, Paris, Rome. Each row has a single 1. The encoder is a transformer, so it follows the fit and transform pattern covered in a later chapter. Note that categories_ ends in an underscore because it is learned from the data during fit.
For ordered (ordinal) categories such as "low", "medium", "high", integer codes do make sense. OrdinalEncoder with an explicit categories list lets you state the order yourself.
Common errors
- A string column reaches
fit. The error is usuallyValueError: could not convert string to float. Encode the column first. - An unseen category at prediction time. By default,
OneHotEncoderraises an error whentransformsees a value it did not meet in training. Passhandle_unknown="ignore"to get an all-zero row instead. - Scaling a one-hot column. Scaling the 0/1 columns is unnecessary. Apply different steps to different columns, which
ColumnTransformerdoes in a later chapter. - Treating an identifier as numeric. User IDs and postal codes look like numbers but carry no quantity. Cast them to strings or drop them.
Exercise
A DataFrame has a column zip_code with integer values such as 10115 and 75001. Should you treat it as numeric or categorical, and why?
Show answer
Categorical. The numbers are identifiers, so their size and differences have no meaning. Cast the column to strings and one-hot encode it, or drop it if it has too many distinct values.