TExcelTAD
Home › Machine Learning › ML Categorical Data

ML Categorical Data

Models do arithmetic, so they need numbers. But many useful columns contain text categories: a city, a colour, a payment method, a product type. You cannot multiply "Berlin" by a coefficient. Before training, categorical columns must be encoded as numbers — and how you do that matters.

The data

An invented table of 10 holiday-flat rentals: the city, whether the flat is furnished, its size class, its area and the nightly price.

python · try it yourself
import pandas as pd

flats = pd.DataFrame({
    "city":     ["Porto", "Lyon", "Porto", "Krakow", "Lyon", "Krakow", "Porto", "Lyon", "Krakow", "Porto"],
    "furnished": ["yes", "no", "yes", "yes", "yes", "no", "no", "yes", "yes", "no"],
    "size":     ["S", "M", "L", "M", "S", "L", "M", "L", "S", "S"],
    "area_m2":  [32, 55, 90, 60, 30, 85, 58, 95, 35, 28],
    "price":    [78, 92, 150, 70, 85, 88, 82, 165, 52, 60],
})
print(flats)
print()
print(flats.dtypes)
     city furnished size  area_m2  price
0   Porto       yes    S       32     78
1    Lyon        no    M       55     92
2   Porto       yes    L       90    150
3  Krakow       yes    M       60     70
4    Lyon       yes    S       30     85
5  Krakow        no    L       85     88
6   Porto        no    M       58     82
7    Lyon       yes    L       95    165
8  Krakow       yes    S       35     52
9   Porto        no    S       28     60

city         object
furnished    object
size         object
area_m2       int64
price         int64
dtype: object

Why not just number the categories?

A tempting shortcut is to replace Porto → 0, Lyon → 1, Krakow → 2. But then a linear model believes Krakow is "twice as much" as Lyon and that Lyon lies between Porto and Krakow — an order that doesn't exist. For nominal categories (no natural order) we need a different encoding.

One-hot encoding

One-hot encoding creates one new 0/1 column per category. A Porto flat gets city_Porto = 1 and 0 in the other city columns. pandas does this with get_dummies:

python · try it yourself
import pandas as pd

flats = pd.DataFrame({
    "city":     ["Porto", "Lyon", "Porto", "Krakow", "Lyon"],
    "furnished": ["yes", "no", "yes", "yes", "yes"],
    "area_m2":  [32, 55, 90, 60, 30],
})
encoded = pd.get_dummies(flats, columns=["city", "furnished"], dtype=int)
print(encoded)
   area_m2  city_Krakow  city_Lyon  city_Porto  furnished_no  furnished_yes
0       32            0          0           1             0              1
1       55            0          1           0             1              0
2       90            0          0           1             0              1
3       60            1          0           0             0              1
4       30            0          1           0             0              1

Numeric columns (area_m2) pass through unchanged. Now a linear model can learn a separate price effect for every city.

Dropping one column

The three city columns always add up to 1, so one of them is redundant: if a flat is neither in Krakow nor Lyon, it must be in Porto. drop_first=True removes the first category of each column. For yes/no columns this leaves a single 0/1 column, which is all you need:

python · try it yourself
import pandas as pd

flats = pd.DataFrame({
    "city":     ["Porto", "Lyon", "Porto", "Krakow", "Lyon"],
    "furnished": ["yes", "no", "yes", "yes", "yes"],
})
print(pd.get_dummies(flats, drop_first=True, dtype=int))
   city_Lyon  city_Porto  furnished_yes
0          0           1              1
1          1           0              0
2          0           1              1
3          0           0              1
4          1           0              1

The dropped category becomes the baseline: each remaining coefficient means "price difference compared with Krakow" (the first city alphabetically).

Training with encoded data

python · try it yourself
import pandas as pd
from sklearn.linear_model import LinearRegression

flats = pd.DataFrame({
    "city":     ["Porto", "Lyon", "Porto", "Krakow", "Lyon", "Krakow", "Porto", "Lyon", "Krakow", "Porto"],
    "furnished": ["yes", "no", "yes", "yes", "yes", "no", "no", "yes", "yes", "no"],
    "area_m2":  [32, 55, 90, 60, 30, 85, 58, 95, 35, 28],
    "price":    [78, 92, 150, 70, 85, 88, 82, 165, 52, 60],
})
X = pd.get_dummies(flats.drop(columns="price"), drop_first=True, dtype=int)
model = LinearRegression().fit(X, flats["price"])

for name, coef in zip(X.columns, model.coef_):
    print(f"{name:14} {coef:7.2f}")
area_m2           1.18
city_Lyon        44.00
city_Porto       35.45
furnished_yes    21.15

Compared with an otherwise identical flat in Krakow, the model expects Lyon and Porto flats to cost more per night, and furnished flats more than unfurnished ones.

OneHotEncoder: the scikit-learn way

get_dummies has a weakness: it only knows the categories present in the table you give it. If a new flat comes from a city never seen in training, the columns won't line up. scikit-learn's OneHotEncoder remembers the categories from fit and can ignore unknown ones:

python · try it yourself
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

train = pd.DataFrame({"city": ["Porto", "Lyon", "Krakow", "Lyon"]})
new = pd.DataFrame({"city": ["Lyon", "Vienna"]})          # Vienna never seen

encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
encoder.fit(train)
print("categories:", encoder.categories_[0].tolist())
print("columns:   ", encoder.get_feature_names_out().tolist())
print(encoder.transform(new))
categories: ['Krakow', 'Lyon', 'Porto']
columns:    ['city_Krakow', 'city_Lyon', 'city_Porto']
[[0. 1. 0.]
 [0. 0. 0.]]

Vienna becomes all zeros instead of crashing the program. In a real project you'd put the encoder inside a pipeline (see ColumnTransformer), so training and prediction always use the same encoding.

Ordinal categories

The size column is different: S < M < L really is an order. For such ordinal data, a single column of ordered integers is appropriate. Tell OrdinalEncoder the correct order explicitly — otherwise it sorts alphabetically (L, M, S), which is wrong:

python · try it yourself
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder

sizes = pd.DataFrame({"size": ["S", "M", "L", "M", "S", "L"]})

alphabetical = OrdinalEncoder().fit_transform(sizes).ravel()
ordered = OrdinalEncoder(categories=[["S", "M", "L"]]).fit_transform(sizes).ravel()
print("alphabetical:", alphabetical)
print("S < M < L:   ", ordered)
alphabetical: [2. 1. 0. 1. 2. 0.]
S < M < L:    [0. 1. 2. 1. 0. 2.]
Encoding Use for Example
One-hot nominal categories (no order) city, colour, payment type
Ordinal ordered categories size S/M/L, rating low/mid/high
Binary 0/1 yes/no columns furnished, has_garden

Tip: One-hot encoding a column with thousands of categories (like user IDs or postcodes) creates thousands of columns. Group rare categories into "other", or use techniques such as target encoding.

Go further: One-Hot, Ordinal and Label Encoding handles unknown and rare categories inside a pipeline and shows the false-order trap of label encoding.

Test yourself

Why is encoding cities as 0, 1, 2 a problem for a linear model?

  1. Numbers are slower than text
  2. It invents an order and distances that don't exist
  3. Models can't use integers
  4. It uses too much memory

How many columns does one-hot encoding (without dropping) create for a column with 4 categories?

  1. 1
  2. 2
  3. 3
  4. 4

Which option lets OneHotEncoder cope with a category it never saw during fit?

  1. drop='first'
  2. handle_unknown='ignore'
  3. sparse_output=False
  4. categories='auto'