Sub topic 2
Know your columns: feature types and what they imply
This chapter assumes you can load data with pandas, know what features and labels are, and have used scikit-learn's fit and predict. It covers how to decide what kind of feature each column is, and how that decision determines which transformations make sense. Later chapters treat each transformation in detail. Here the goal is to pick the right branch before you start.
Why the type is a decision, not a fact
A pandas dtype describes how values are stored. It does not describe what the values mean. A column of integers might be a count, a rating from 1 to 5, a ZIP code, or a database ID. All four are int64, and each needs different handling.
The type you assign should come from asking three questions:
- Do arithmetic operations on the values mean anything? Is the difference between 40 and 50 the same kind of thing as the difference between 10 and 20?
- Do the values have a natural order?
- How many distinct values are there, and will new ones appear after training?
The answers decide the scaling, encoding, imputation strategy and even whether the column should be a feature at all.
The main feature types
Numeric
Numeric columns hold quantities where distance and magnitude carry meaning.
- Continuous values can take any value in a range, such as income, temperature or duration. These are candidates for scaling and for skew-reducing transforms.
- Discrete counts are non-negative integers, such as the number of purchases. They are often right-skewed and often have many zeros. A zero can mean "none happened", which is different from "unknown".
Categorical
Categorical columns hold labels from a set.
- Nominal categories have no order, such as city, browser or product type.
- Ordinal categories have a meaningful order but unequal or unknown spacing, such as
low < medium < highor education level. - Binary columns have two values, such as yes/no. They can be stored as 0 and 1 directly.
- High-cardinality categories have hundreds or thousands of levels, such as merchant or user agent. One-hot encoding these produces very wide, sparse matrices, so they usually need a different approach (see the target encoding chapter).
Date-time
A timestamp is a number, but feeding it in raw is rarely useful. Its value comes from components such as hour, weekday, month and elapsed time since an event. These components can be cyclical (hour 23 is next to hour 0), which a plain integer does not capture.
Text
Free text has an unbounded vocabulary. A column of customer comments cannot be treated as categorical, because almost every value is unique. It needs its own representation, such as word counts or length features.
Identifiers
IDs such as customer_id or order_number are labels that look numeric. Usually they should be dropped. A model can memorize them, and they do not generalize to new rows. The exception is when an ID encodes something real (for example, sequential IDs that reflect signup order), and then you should extract that meaning deliberately.
What each type implies
| Type | Typical treatment | Common trap |
|---|---|---|
| Continuous numeric | Impute, scale, maybe log transform | Scaling before splitting the data |
| Count | Impute with 0 only if 0 means "none", maybe log1p | Treating missing as zero |
| Nominal categorical | One-hot encode | Integer codes that imply a false order |
| Ordinal categorical | Ordinal encode with an explicit category order | Alphabetical default ordering |
| High-cardinality categorical | Target or frequency encoding, grouping rare levels | One-hot explosion |
| Date-time | Extract parts, cyclical encoding, elapsed time | Using the raw timestamp or ignoring time zones |
| Text | Length, counts, TF-IDF | Treating it as categorical |
| Identifier | Usually drop | Letting the model memorize rows |
Which models care
The type also interacts with the algorithm. Linear models, k-nearest neighbors, SVMs and neural networks are sensitive to feature scale, and they treat integer codes as real numbers. Tree-based models split on thresholds, so they are indifferent to monotonic rescaling. They can also cope with an arbitrary integer code for a category, though that code can make splits inefficient. Even so, the missing-value handling and categorical encoding choices matter for trees too. Decide the type first, then check whether your model needs the scaling step.
Inspecting a dataset
dtypes alone mislead, so profile each column: its dtype, its number of distinct values, its missing count, and an example. The following code builds a small table with a deliberate trap (zip_code is an integer but is really a category) and then fixes the types.
import pandas as pd
df = pd.DataFrame({
"customer_id": [1001, 1002, 1003, 1004],
"age": [34, 51, None, 28],
"income": [52000.0, 87000.0, 61000.0, None],
"zip_code": [10001, 94105, 10001, 60601],
"city": ["NYC", "SF", "NYC", None],
"plan": ["basic", "pro", "basic", "enterprise"],
"signup": pd.to_datetime(
["2023-01-15", "2023-06-02", "2024-02-20", "2024-03-01"]
),
"comment": [
"Great service",
"Slow support, but fixed quickly",
"Love it",
"Billing was confusing",
],
})
profile = pd.DataFrame({
"dtype": df.dtypes.astype(str),
"n_unique": df.nunique(),
"missing": df.isna().sum(),
"example": df.iloc[0],
})
print(profile)
# Decisions made by a human, not by the dtype
df = df.drop(columns=["customer_id"]) # identifier
df["zip_code"] = df["zip_code"].astype(str) # a label, not a quantity
numeric_cols = ["age", "income"]
categorical_cols = ["city", "plan", "zip_code"]
datetime_cols = ["signup"]
text_cols = ["comment"]After this step each column belongs to exactly one list. Those lists are what you later hand to a ColumnTransformer. Writing them down explicitly is deliberate. If you let a selector pick columns by dtype, a new column or a changed dtype upstream can silently route a column to the wrong branch.
A decision flow
The flow below summarizes the questions to ask for each column.
Edge cases that change the answer
- Numbers stored as strings. A column with values like
"1,200"or"N/A"loads asobject. Convert it withpd.to_numeric(..., errors="coerce")after cleaning, and check how many values turn intoNaN. - Sentinel values. Codes such as
-1,999or0for "unknown" look like real numbers. Replace them withNaNso the imputer sees them as missing, or the scaler will treat them as data. - Numeric ratings. A 1 to 5 rating is ordinal. Using it as a number assumes equal spacing between levels. That is often acceptable, but it is an assumption. Compare it with a categorical treatment if the column matters.
- Booleans with missing values. A boolean column with missing entries becomes
objectin pandas. Decide whether missing is its own third state. - Categories unseen at serving time. A new city can appear in production. Plan for it now, for example with
OneHotEncoder(handle_unknown="ignore"). - Drifting cardinality. A column with 12 levels in training may have 15 in production. A low-cardinality column today can become high-cardinality as the business grows.
Data leakage starts here
Type decisions can leak information. An identifier that correlates with the label (for example, IDs assigned after a customer churned) gives inflated scores that vanish in production. A column that is only populated after the outcome, such as a "cancellation reason", is also leakage, and it is easy to spot only if you ask when each column is recorded. Add this fourth question for every column: at prediction time, will this value exist, and will it be the same kind of value?
Exercise
A dataset has a column store_id with integer values from 1 to 480, a column rating with values 1 to 5, and a column last_login containing timestamps. For each column, state its feature type and one appropriate treatment, and explain why leaving store_id as a plain number is risky.
Show answer
store_id is a high-cardinality nominal categorical (or an identifier if it adds no meaning). Treat it with target or frequency encoding, or drop it. Leaving it numeric is risky because linear and distance-based models would treat store 400 as "more" than store 12 and fit a meaningless slope. rating is ordinal. Use ordinal encoding with the order 1 to 5, or treat it as numeric if equal spacing is a reasonable assumption. last_login is date-time. Extract components such as hour and weekday, or compute elapsed time since login relative to a reference date, rather than using the raw timestamp.
Exercise
A column days_since_last_purchase contains the value 9999 for customers who never purchased. What problem does this cause when you scale the column, and what should you do instead?
Show answer
The value 9999 is a sentinel, not a real duration. It inflates the mean and standard deviation, so StandardScaler compresses all real values into a narrow range, and models read the sentinel as an extreme value. Replace 9999 with NaN, impute the numeric values as usual, and add a missing-value indicator (or a separate "never purchased" flag) so the model can still use the fact that no purchase occurred.