Sub topic 9
Feature names and sparse output
This chapter assumes you can fit and transform with OneHotEncoder, and that you know pandas DataFrames and NumPy arrays. It covers two practical details of the encoder's output: how to label the new columns, and why the result is often not a normal array.
Naming the encoded columns
One-hot encoding turns one column into several. After that you need to know which output column came from which category. Fitted encoders provide get_feature_names_out() for this. Each name has the form column_category.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({
"color": ["red", "green", "blue", "green"],
"size": ["S", "M", "S", "L"],
})
enc = OneHotEncoder()
X = enc.fit_transform(df)
print(type(X))
print(X.shape, X.nnz)
print(enc.get_feature_names_out())The names come out in the same order as the matrix columns: color_blue, color_green, color_red, size_L, size_M, size_S. Categories within a feature are sorted alphabetically. Use these names to label coefficients, feature importances, or a DataFrame you build for inspection.
Why the output is sparse
The first print shows a SciPy csr_matrix, not a NumPy array. By default, OneHotEncoder returns a sparse matrix. A sparse matrix stores only the nonzero entries and their positions.
One-hot rows are almost all zeros. Each row has exactly one 1 per input feature. X.nnz is the number of stored nonzero values. Here it is 8: 4 rows times 2 features.
The saving grows with the number of categories. Take 100,000 rows and one feature with 1,000 categories:
- A dense float64 array needs 100,000 × 1,000 × 8 bytes, which is 800 MB.
- A sparse matrix stores 100,000 nonzero values plus their index arrays, roughly 1.6 MB.
| Setting | Result type | Best for |
|---|---|---|
| `sparse_output=True` (default) | SciPy sparse matrix | Many categories, large data, linear models |
| `sparse_output=False` | NumPy array | Small data, inspection, tools that need dense input |
Getting a readable DataFrame
Printing a sparse matrix shows coordinate triples, not a grid. To inspect it, convert it with toarray() and attach the names:
readable = pd.DataFrame(X.toarray(), columns=enc.get_feature_names_out())
print(readable)Only do this on small data. toarray() allocates the full dense array, which defeats the memory saving.
If you want DataFrames from the encoder directly, turn sparse output off and ask for pandas output:
enc = OneHotEncoder(sparse_output=False).set_output(transform="pandas")
encoded = enc.fit_transform(df)
print(encoded.columns.tolist())The result keeps the input index, so rows stay aligned with the original data.
Names inside a ColumnTransformer
A ColumnTransformer prefixes each name with the step name, for example cat__city_Paris and num__age. Pass verbose_feature_names_out=False to drop the prefixes. Do this only when the names cannot collide, because two steps producing the same name raises an error.
Common errors
TypeErroraboutsparse. Older tutorials useOneHotEncoder(sparse=False). That argument was renamedsparse_outputin scikit-learn 1.2 and removed later. Usesparse_output.- Error from
set_output(transform="pandas"). Pandas output cannot hold the default sparse matrix. Setsparse_output=Falseas well. - Wrong column labels. Do not hand-write a column list. The order depends on the fitted categories, so always call
get_feature_names_out()on the fitted encoder. - Out-of-memory errors after
toarray(). Keep the matrix sparse. Many scikit-learn estimators, such asLogisticRegressionandRidge, accept sparse input directly.
Exercise
You fit OneHotEncoder() on a column with 5,000 distinct values and 200,000 rows. A teammate suggests sparse_output=False so the result is easier to print. Give one reason to refuse, and say how to inspect a few encoded rows safely.
Show answer
A dense float64 array would need 200,000 × 5,000 × 8 bytes, about 8 GB, while the sparse matrix stores only 200,000 nonzero values. Keep the default sparse output. To inspect rows, slice first and densify only the slice, for example pd.DataFrame(X[:5].toarray(), columns=enc.get_feature_names_out()).