Sub topic 9
Feature names and sparse output
One-hot encoding turns one column into many, so two practical questions follow. How do you know which output column is which, and how do you store a matrix that is mostly zeros? This chapter covers how OneHotEncoder answers both.
What this chapter assumes
You should be able to fit and transform with OneHotEncoder on a DataFrame, as covered in the previous chapters. You should also know what a NumPy array is and what shape means. No prior knowledge of SciPy is needed. The examples use scikit-learn 1.2 or newer. The sparse_output parameter was called sparse in older versions.
Why the output is sparse by default
A one-hot row contains exactly one 1 per encoded feature. The other entries are 0. With 1,000 categories, a row is 99.9% zeros. Storing every zero wastes memory and slows down arithmetic.
OneHotEncoder therefore returns a SciPy sparse matrix by default. It stores only the nonzero entries and their positions.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({
"color": ["red", "green", "blue", "green"],
"size": ["S", "M", "L", "M"],
})
enc = OneHotEncoder()
out = enc.fit_transform(X)
print(type(out))
print(out.shape, out.nnz)
print(out.toarray())
print(enc.get_feature_names_out())The result is a scipy.sparse CSR matrix (compressed sparse row). Its shape is (4, 6): three color columns plus three size columns. nnz is the number of stored nonzero entries. It is 8 here, because each of the 4 rows has one 1 for color and one for size.
Printing the sparse object itself shows coordinate and value pairs, not a grid. Call toarray() when you want to look at the grid.
How CSR stores the data
CSR keeps three arrays. You rarely touch them directly, but they explain the memory behavior.
| Array | Meaning | Value for the example above |
|---|---|---|
| `data` | The nonzero values, row by row | `[1, 1, 1, 1, 1, 1, 1, 1]` |
| `indices` | The column of each stored value | `[2, 5, 1, 4, 0, 3, 1, 4]` |
| `indptr` | Where each row starts in `data` | `[0, 2, 4, 6, 8]` |
Row 0 is red, S. It owns entries 0 and 1 of indices, which are columns 2 (color_red) and 5 (size_S). Storage grows with the number of nonzeros, which is rows times encoded features. It does not grow with the number of categories.
The memory difference at scale
The next example encodes 100,000 rows of a feature with about 1,000 categories and compares the two storage costs.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
rng = np.random.default_rng(0)
codes = rng.integers(0, 1000, size=(100_000, 1))
X = np.char.add("id_", codes.astype(str))
enc = OneHotEncoder()
out = enc.fit_transform(X)
sparse_bytes = out.data.nbytes + out.indices.nbytes + out.indptr.nbytes
dense_bytes = out.shape[0] * out.shape[1] * out.dtype.itemsize
print(out.shape)
print(f"sparse: {sparse_bytes / 1e6:.1f} MB")
print(f"dense: {dense_bytes / 1e6:.1f} MB")The dense version needs about 800 MB (100,000 × 1,000 × 8 bytes). The sparse version needs a little over 1 MB. Passing dtype=np.float32 to the encoder halves the stored values again, if your model accepts it.
Feature names
A matrix has no column labels, so you need a way to recover which column came from which category. The fitted encoder provides this.
get_feature_names_out()returns an array of names in column order, formatted as<feature>_<category>.categories_is a list with one array of categories per input feature.
The prefix depends on the input type.
| Input to `fit` | Names produced |
|---|---|
| DataFrame | The DataFrame column names, such as `color_red` |
| NumPy array | Generic names, such as `x0_red` |
| NumPy array plus names passed to `get_feature_names_out` | Your names, such as `color_red` |
For a NumPy array, supply the names yourself:
import numpy as np
from sklearn.preprocessing import OneHotEncoder
X = np.array([["red", "S"], ["green", "M"], ["blue", "L"]])
enc = OneHotEncoder().fit(X)
print(enc.get_feature_names_out())
print(enc.get_feature_names_out(["color", "size"]))The first call prints x0_... and x1_... names. The second prints color_... and size_....
Names reflect the options you chose. With drop="first", the dropped category has no name in the output. With min_frequency or max_categories, grouped rare categories appear as a single column named like color_infrequent_sklearn. Always take names from the fitted encoder instead of building them by hand, so they stay in sync with the columns.
In scikit-learn 1.3 and later, you can change the format with the feature_name_combiner parameter. It takes a function (feature, category) -> str. For example, lambda f, c: f"{f}={c}" gives names like color=red.
Using names to read a model
Names make coefficients interpretable. Each coefficient of a linear model belongs to one indicator column.
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({"city": ["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome"]})
y = [0, 1, 0, 1, 1, 0]
enc = OneHotEncoder()
Xt = enc.fit_transform(X)
clf = LogisticRegression().fit(Xt, y)
for name, coef in zip(enc.get_feature_names_out(), clf.coef_[0]):
print(f"{name}: {coef:.2f}")LogisticRegression accepts the sparse matrix directly. No conversion is needed.
Getting dense output when you need it
You have two options, and they differ in cost.
- Construct the encoder with
sparse_output=False. The transform returns a NumPy array directly. - Keep the default and call
.toarray()on the result when needed.
The first option is simpler when you know you want dense data. The second lets you keep the sparse matrix for training and densify only a small slice for inspection, for example out[:5].toarray().
To get a labeled DataFrame, combine dense output with the feature names:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({"color": ["red", "green", "blue"]})
enc = OneHotEncoder(sparse_output=False)
encoded = pd.DataFrame(
enc.fit_transform(X),
columns=enc.get_feature_names_out(),
index=X.index,
)
print(encoded)Passing index=X.index keeps the row labels aligned with the original data. Without it, a filtered or shuffled DataFrame gets a fresh 0..n-1 index, and a later join silently misaligns rows.
Scikit-learn can also return DataFrames for you through enc.set_output(transform="pandas"). This needs sparse_output=False, because pandas output does not support sparse matrices. Using both together raises a ValueError.
Sparse input and the rest of your pipeline
Many estimators handle sparse input well, including linear models, LogisticRegression, SGDClassifier, and tree ensembles in recent versions. Some steps do not behave the same way.
StandardScalerraises an error on sparse input with the defaultwith_mean=True. Centering would turn the zeros into nonzero values and destroy the sparsity. Usewith_mean=False, or scale only the numeric columns before they meet the encoded ones.- Some estimators and utilities convert sparse input to dense internally, which silently brings the memory cost back. Check the documentation for
accept_sparse-style behavior if memory is tight. - When you combine encoded and numeric columns with
ColumnTransformer, it decides the final format itself. If the overall density of the stacked result is below itssparse_threshold(default0.3), it returns a sparse matrix. Otherwise it returns a dense array. The next chapters cover this in detail.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Output looks like `(0, 2) 1.0` lines | You printed a sparse matrix | Use `.toarray()` for display |
| `MemoryError` after encoding | A dense conversion of a high-cardinality column | Stay sparse, or reduce categories |
| Names are `x0_...` | The encoder was fitted on a NumPy array | Pass names to `get_feature_names_out` |
| Columns and names disagree in length | Names were built by hand, or the encoder was refitted with different options | Take names from the same fitted encoder |
| `TypeError: __init__() got an unexpected keyword argument 'sparse_output'` | scikit-learn older than 1.2 | Upgrade, or use `sparse=False` |
| `ValueError` from `StandardScaler` on sparse data | Centering sparse data | Set `with_mean=False` |
Exercise
Exercise
You fit OneHotEncoder(drop="first") on a DataFrame with a size column containing "large", "medium" and "small". You then call fit_transform and get a matrix with 2 columns. How do you find out which column is which, and what is the shape of the output if you also set sparse_output=False and the DataFrame has 10 rows?
Show answer
Call enc.get_feature_names_out() on the fitted encoder. It returns ["size_medium", "size_small"], because "large" is first alphabetically and is dropped. With sparse_output=False, fit_transform returns a dense NumPy array of shape (10, 2). With the default, it returns a sparse CSR matrix of the same shape.