Sub topic 1
Categorical features and why models need numbers
Most tabular datasets mix numbers with labels such as a city name, a subscription plan or a product type. Machine learning models can only compute with numbers. This chapter explains what categorical features are, how to spot them in a DataFrame, and why they must be converted before most models can use them. The rest of the tutorial covers the conversion itself.
Prerequisites
This chapter assumes you have:
- Basic Python and pandas skills, including creating a DataFrame and reading its
dtypes. - Familiarity with NumPy arrays and the idea of a feature matrix: a 2D array with one row per example and one column per feature.
- A basic idea of training and test splits, meaning that a model learns from one portion of the data and is judged on another.
You will need pandas and scikit-learn installed to run the code.
What a categorical feature is
A categorical feature takes its values from a limited set of labels. Each label is a category, and the set of possible labels is the feature's vocabulary. Examples:
country: "France", "Japan", "Brazil"plan: "basic", "standard", "premium"browser: "Chrome", "Firefox", "Safari"is_member: "yes", "no"
A numeric feature such as age or price is different. Arithmetic on it means something: 40 is twice 20, and the average of 30 and 50 is 40. Arithmetic on labels means nothing. "Paris" plus "Rome" has no sensible result, and neither does the average of "Chrome" and "Safari".
Storage type does not decide whether a feature is categorical. The meaning does. Three common cases:
- A ZIP code like
"10115"is an identifier. It looks like a number but is a label, because the number 75001 is not "bigger" than 10115 in any useful way. - A rating given as the integers 1 to 5 is stored as a number and does have an order. Whether it behaves like a measurement is a modelling decision.
- A status code like 404 or 500 is a label even though it is an integer.
Spotting categorical columns in code
pandas often stores text columns with the object dtype, and newer versions use a dedicated string dtype. It also offers an explicit category dtype. A reliable way to find non-numeric columns that works across versions is to test for numeric dtypes directly.
import pandas as pd
from pandas.api.types import is_numeric_dtype
df = pd.DataFrame({
"city": ["Paris", "Berlin", "Rome", "Paris"],
"plan": ["basic", "premium", "basic", "standard"],
"zip_code": ["75001", "10115", "00100", "75002"],
"age": [25, 32, 47, 51],
"n_orders": [3, 10, 1, 7],
})
print(df.dtypes)
categorical_cols = [c for c in df.columns if not is_numeric_dtype(df[c])]
numeric_cols = [c for c in df.columns if is_numeric_dtype(df[c])]
print("categorical:", categorical_cols)
print("numeric:", numeric_cols)
for col in categorical_cols:
print(col, "->", df[col].nunique(), "distinct values")The code prints city, plan and zip_code as categorical, and age and n_orders as numeric. The loop also reports the number of distinct values in each categorical column. This count is the column's cardinality, and it matters later. A column with three categories adds a few columns after encoding. A column with ten thousand categories can add ten thousand.
Notice that zip_code was written as strings. Strings keep the leading zero in "00100", whereas an integer would turn it into 100. If a label-like column was loaded as integers, check the data source before you decide how to treat it.
Why models need numbers
Each model family works with numbers in its own way. In all of them, strings have no defined operation.
- Linear and logistic regression compute a weighted sum of the features,
w1*x1 + w2*x2 + ... + b. Eachxhas to be a number to be multiplied by a weight. - Neural networks multiply input vectors by weight matrices. They need numeric tensors.
- k-nearest neighbours and SVMs with common kernels measure distances or dot products between rows. A distance between "Paris" and "Rome" is undefined.
- Gradient-based training of any model needs derivatives with respect to numeric inputs and parameters.
- Decision trees split on thresholds such as
age <= 40. A threshold needs an ordering, which arbitrary labels do not have.
scikit-learn estimators therefore convert input to a float array when you call fit. If a column contains text, that conversion fails.
from sklearn.linear_model import LogisticRegression
X = df[["city", "age"]]
y = [0, 1, 0, 1]
try:
LogisticRegression().fit(X, y)
except ValueError as err:
print("Error:", err)The error message says that a string could not be converted to a float, and it names the first offending value, such as 'Paris'. This is the most common first symptom of an unencoded categorical column, and the fix is to encode before you fit.
The encoding step in the workflow
Encoding is a preprocessing step. It sits between the raw table and the model, and it must produce a purely numeric feature matrix.
Two requirements follow from this picture, and later chapters develop both:
- The encoding must be consistent. If "Rome" becomes column 3 during training, it must become column 3 at prediction time too. The same learned mapping has to be reused on every new batch of data.
- The encoding must be learned from training data only. The mapping is derived from the data, so it belongs to the training step. Computing it on the whole dataset lets information about the test set leak into your pipeline.
Why you cannot simply number the labels
The obvious fix is to replace each label with an integer, for example Paris = 0, Berlin = 1, Rome = 2. This does produce a numeric column, and the code runs without errors. The problem is subtler: the model now sees Rome as "larger" than Berlin and twice as far from Paris as Berlin is. Those relationships come from the arbitrary order in which you numbered the labels, not from the data. The chapter on integer codes explores this in detail. For now, remember that a type conversion that merely passes fit is not necessarily a correct encoding.
One-hot encoding avoids the problem by giving each category its own column of 0s and 1s. The chapters that follow introduce it step by step.
Common mistakes at this stage
| Mistake | Consequence | What to do |
|---|---|---|
| Assuming every integer column is numeric | Identifiers or codes are treated as quantities | Check what each integer column means before you model it |
| Assuming every text column is categorical | Free text such as reviews has thousands of unique values and needs different treatment | Check `nunique()` and look at sample values |
| Casting labels to integers just to make `fit` run | The model learns from an invented order | Use a proper encoding |
| Ignoring cardinality | Very wide matrices, slow training, overfitting | Count distinct values per column early |
| Encoding before the train/test split | Information from the test set shapes the encoder | Split first, then fit the encoder on training data only |
Summary
A categorical feature holds labels from a limited vocabulary. Models compute with sums, distances and thresholds, so they need numbers, and a text column makes fit fail. Which columns are categorical depends on what the values mean, not on how they are stored. Check each column's meaning and cardinality before you choose an encoding. The next chapter separates categories that have a natural order from those that do not, because that distinction decides which encoding is appropriate.
Exercise
A DataFrame has a column product_id stored as integers (for example 1042, 2077, 3150). A teammate says it is already numeric, so it can go straight into a linear regression. Is that a safe choice? Explain, and name one number you would compute to understand how costly encoding it would be.
Show answer
It is not safe. The integers are identifiers, so they are labels, and a linear model would treat 3150 as three times as large as 1042 and learn a single weight for that meaningless scale. The column should be treated as categorical and encoded. To judge the cost of one-hot encoding it, compute the column's cardinality with df["product_id"].nunique(), because one-hot encoding creates roughly one column per distinct value.
Exercise
Why does LogisticRegression().fit(X, y) raise a ValueError when X contains a column of city names, and what must be true of the data before it can be fitted?
Show answer
The estimator converts the input to a float array, and a string like "Paris" cannot be converted to a float. Before fitting, every column must be numeric, so categorical columns need to be encoded into numbers first, using a mapping learned from the training data only.