Sub topic 2
Know your columns: feature types and what they imply
This chapter assumes you know basic pandas, the supervised learning vocabulary (features, labels, train and test sets), and the scikit-learn fit and predict workflow. The first step in feature engineering is to classify each column. The type tells you which treatment fits and which treatments would be wrong.
The main feature types
Most tabular columns fall into one of these groups.
| Type | Examples | Typical treatment |
|---|---|---|
| Numeric continuous | age, income, price | Impute, scale, maybe log transform |
| Numeric discrete (counts) | number of visits | Often used as is, sometimes log transformed |
| Categorical nominal | city, color | One-hot or target encoding |
| Categorical ordinal | size (S, M, L), rating | Ordinal encoding that keeps the order |
| Binary | is_member | Map to 0 and 1 |
| Date-time | signup timestamp | Extract calendar parts |
| Text | review, job title | Counts, TF-IDF, or length features |
| Identifier | user_id, order_id | Usually drop |
Types are about meaning, not storage. A column of ZIP codes may be stored as integers, but it is categorical, because the distance between 10001 and 10002 means nothing. A column of star ratings stored as strings is ordinal.
Why the type matters
The treatment depends on what the model can do with the values.
- Linear models, neural networks and distance-based models treat numbers as quantities. If you feed in city codes 1, 2 and 3, the model assumes city 3 is "more" than city 1. One-hot encoding avoids this.
- Tree models split on thresholds. They don't need scaling, and they cope with monotonic transforms. They still need categories turned into numbers in scikit-learn.
- Ordinal columns lose information if you one-hot encode them, because the order disappears.
- Identifier columns let a model memorize rows. They add noise and can give a good training score that does not carry over to new data.
Inspecting your data
Start with dtypes, then check cardinality, which is the number of distinct values in a column. High cardinality changes the encoding choice.
import pandas as pd
df = pd.DataFrame({
"user_id": [101, 102, 103, 104],
"age": [34, 28, None, 45],
"income": [52000, 61000, 48000, None],
"city": ["Paris", "Lyon", "Paris", None],
"size": ["S", "M", "L", "M"],
"signup": ["2024-01-05", "2024-02-11", "2024-02-20", "2024-03-02"],
})
print(df.dtypes)
print(df.nunique())
print(df.isna().sum())Then record your decisions in lists. The same lists will feed a ColumnTransformer in a later chapter.
df["signup"] = pd.to_datetime(df["signup"])
numeric_cols = ["age", "income"]
categorical_cols = ["city"]
ordinal_cols = ["size"]
datetime_cols = ["signup"]
drop_cols = ["user_id"]You can also let pandas propose a first guess with select_dtypes. Treat it as a draft, since it will label ZIP codes as numeric.
auto_numeric = df.select_dtypes(include="number").columns.tolist()
auto_object = df.select_dtypes(include="object").columns.tolist()
print(auto_numeric, auto_object)Common errors
- Treating codes as quantities. Integer-coded categories such as
region=3should not go into a linear model as numbers. - Leaving dates as strings. A string date cannot give you month or weekday until you convert it with
pd.to_datetime. - Keeping IDs as features. Row identifiers can leak information, for example when IDs are assigned in time order.
- Using the number of distinct values blindly. A categorical column with 50,000 values makes one-hot encoding very wide. Look at cardinality before choosing.
Where this leads
The type map becomes a plan. Numeric columns go to imputation and scaling, categorical columns go to encoders, and datetime columns go to feature extraction. The rest of the tutorial covers each treatment in turn.
Exercise
A column named "zip_code" holds integers such as 94105 and 10001, and you plan to use logistic regression. Which type is this column, and how should you treat it?
Show answer
It is categorical (nominal), even though it is stored as an integer. Treat it as a category, for example with one-hot encoding, or with target encoding if there are many distinct codes. Feeding the raw integers to logistic regression would imply that a larger ZIP code means more of something, which has no meaning.
Exercise
Why should you usually drop a column such as "order_id" before training?
Show answer
An identifier is unique per row and carries no general pattern. A model can use it to memorize training rows, and if IDs are assigned in time order it can leak information that will not be available in the same way at prediction time.