Sub topic 12
Mixing numeric and categorical columns
This chapter assumes you can fit a LinearRegression and read coef_. It also assumes you know how Pipeline and StandardScaler work and that you can handle a pandas DataFrame. By the end you will encode text columns for a linear model, route columns to different transformers, and avoid three common mistakes: the dummy variable trap, unseen categories at predict time, and leakage.
Why linear models need encoding
A linear model computes y = Xw + b. Every column in X must be a number, because each one is multiplied by a weight. A column holding "a", "b" and "c" has no meaningful numeric value. Mapping the labels to 0, 1 and 2 would tell the model that city c is twice city b, and that is almost never true.
One-hot encoding avoids this. It replaces one categorical column with one 0/1 column per category. Each category then gets its own weight, which acts as an offset from a baseline.
The numeric columns still need their own handling, such as scaling. So you need a tool that applies different transformers to different columns and puts the results side by side. That tool is ColumnTransformer.
The working model
ColumnTransformer takes a list of (name, transformer, columns) triples. During fit, it fits each transformer on its own columns only. During transform, it applies each transformer and concatenates the outputs horizontally.
Here is a complete example with a small housing table.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"area": [50, 80, 120, 65, 95, 150, 70, 110],
"city": ["a", "b", "a", "c", "b", "c", "a", "b"],
"price": [150, 260, 330, 190, 300, 420, 200, 340],
})
X = df[["area", "city"]]
y = df["price"]
pre = ColumnTransformer([
("num", StandardScaler(), ["area"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = make_pipeline(pre, LinearRegression())
model.fit(X, y)
print(model.predict(pd.DataFrame({"area": [100], "city": ["b"]})))The pipeline accepts a raw DataFrame, including the text column, at both fit and predict. The encoder and scaler learn their parameters (the categories, the mean and the standard deviation) from the training data only. Putting the transformers in the pipeline is what keeps them from seeing test data.
Columns can be given by name or by rule
Listing columns by hand is clear, but it breaks when the schema changes. make_column_selector picks columns by dtype instead.
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"area": [50, 80, 120, 65, 95, 150, 70, 110],
"city": ["a", "b", "a", "c", "b", "c", "a", "b"],
"price": [150, 260, 330, 190, 300, 420, 200, 340],
})
X = df[["area", "city"]]
y = df["price"]
pre = ColumnTransformer([
("num", StandardScaler(), make_column_selector(dtype_include="number")),
("cat", OneHotEncoder(drop="first"), make_column_selector(dtype_exclude="number")),
])
model = make_pipeline(pre, LinearRegression()).fit(X, y)
names = model[0].get_feature_names_out()
for name, coef in zip(names, model[-1].coef_):
print(f"{name}: {coef:.2f}")
print("intercept:", round(model[-1].intercept_, 2))get_feature_names_out() returns names such as num__area and cat__city_b. The prefix is the step name from the ColumnTransformer. Always pair these names with coef_. After encoding, the columns no longer match your original DataFrame, and the order is easy to get wrong if you do it by eye.
I selected the categorical columns with dtype_exclude="number" instead of dtype_include="object". Recent pandas versions can store text in a dedicated string dtype, and an object filter would miss those columns.
The dummy variable trap
The three city columns always sum to 1 for every row. The intercept column, which is implicitly all ones, is therefore a linear combination of them. The design matrix is rank deficient, so infinitely many weight sets give identical predictions.
LinearRegression does not fail here, because it uses a least-squares solver that tolerates this. The problem is interpretation: the individual city weights are no longer unique, and you cannot read them as offsets from anything.
drop="first" removes one category per feature, and that category becomes the baseline. The remaining weights then mean "difference from the dropped city, holding area fixed." Use drop="first" for plain OLS when you plan to read coefficients. With Ridge, Lasso or ElasticNet, the penalty already picks a unique solution, so you can keep all columns. Note that the penalty shrinks each category toward zero, not toward a baseline.
Unseen categories at predict time
By default OneHotEncoder raises an error if predict sees a category it did not see during fit. That is safe, but it can break a production service. With handle_unknown="ignore", the unknown value becomes a row of all zeros.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"area": [50, 80, 120, 65, 95, 150, 70, 110],
"city": ["a", "b", "a", "c", "b", "c", "a", "b"],
"price": [150, 260, 330, 190, 300, 420, 200, 340],
})
pre = ColumnTransformer([
("num", StandardScaler(), ["area"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = make_pipeline(pre, Ridge(alpha=1.0)).fit(df[["area", "city"]], df["price"])
known = pd.DataFrame({"area": [100], "city": ["b"]})
unseen = pd.DataFrame({"area": [100], "city": ["z"]})
print("known city:", model.predict(known))
print("unseen city:", model.predict(unseen))The unseen prediction runs without error, but it silently contains no city effect. That means the model treats the city as having a weight of zero, not as an average city. Treat this as a fallback and log how often it happens. If many rows hit it, the training data does not represent your inputs.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `could not convert string to float` | A text column went to the regressor without encoding | Add it to the `OneHotEncoder` branch |
| `Found unknown categories` at predict | Encoder default is `handle_unknown="error"` | Use `handle_unknown="ignore"` or retrain with more data |
| Columns missing from the output | `ColumnTransformer` drops unlisted columns by default | List every column you need, or set `remainder="passthrough"` |
| `ValueError` on NaN | `StandardScaler` accepts NaN, but `LinearRegression` does not | Add `SimpleImputer` to the numeric branch |
| Coefficients cannot be compared | Mixed scaled and unscaled columns, or a missing baseline | Scale numeric columns and use `drop="first"` for OLS |
| Wildly different scores between runs | Encoder fit on the full dataset before splitting | Put the encoder in the pipeline and fit on training data only |
remainder="passthrough" deserves a caution. Passed-through columns are not scaled, so a penalized model such as Ridge will treat them unfairly. Prefer to route every column explicitly.
Cross-validation and the high-cardinality limit
A pipeline with a ColumnTransformer works directly in cross_val_score. On every fold, the scaler and encoder are refit on the training part only, which is what you want. Pass the raw DataFrame as X, not an array, so the column names are still available.
One-hot encoding adds a column per category. A feature such as postal code with thousands of values creates thousands of columns, and most of them are nearly empty. OLS will overfit this badly. Ridge or Lasso with a tuned alpha is the usual response. For very high cardinality, OneHotEncoder(min_frequency=...) groups rare categories into one shared column, and target-based encoders are an alternative that needs their own leakage care.
Exercise
You fit make_pipeline(ColumnTransformer([("cat", OneHotEncoder(), ["city"]), ("num", StandardScaler(), ["area"])]), LinearRegression()) on a table with columns area, city and rooms. The predictions run, but rooms has no effect on them. Why, and what are two ways to fix it?
Show answer
ColumnTransformer drops any column that is not listed, and remainder defaults to "drop". The rooms column never reaches the regressor. Fix it by adding rooms to the numeric branch (["area", "rooms"]), or by setting remainder="passthrough" (though then rooms stays unscaled, which matters for Ridge or Lasso).
Exercise
Why can you not interpret the individual city weights from LinearRegression when OneHotEncoder keeps all categories and the model has an intercept?
Show answer
The one-hot columns sum to 1 in every row, so they duplicate the intercept column. The design matrix is rank deficient and many different weight sets give the same predictions. Use drop="first" (or a regularized model) to get a unique, interpretable solution.