Categories are not numbers.
Represent labels such as city or product type without inventing an order between them.
Start with the meaning.
A categorical feature takes one of several named values: city, color, plan type, or device kind. A model that expects numbers cannot directly multiply the string 'blue' by a coefficient. Replacing categories with 0, 1, and 2 is tempting, but it can invent a false order and distance. A linear model may conclude that category 2 is twice category 1 or lies one unit beyond it. When the names have no natural order, the numeric codes should not imply one.
One-hot encoding makes a separate indicator column for each known category. For color with red, green, and blue, a red row can become [1, 0, 0] and a blue row [0, 0, 1]. The positions have meaning only because an encoder learned and stored a category order. New inputs must use that same encoder, or the positions can silently change meaning. An unseen category needs an explicit policy such as ignoring it, grouping it as unknown, or rejecting the row.
How the idea works.
Some categories are genuinely ordered: small, medium, large. An ordinal encoding can preserve that order, though the gaps between levels may still not be equal. Other categories have many unique values, such as postal codes or product IDs. One-hot encoding thousands of rare values can create a very wide sparse table. Depending on the task, grouping rare categories, hashing, or a carefully validated alternative representation may be more useful.
Never fit category mappings on test rows if the mapping learns from data. This is the same leakage principle as scaling. A ColumnTransformer can send numeric columns through imputation and scaling while sending categorical columns through imputation and one-hot encoding. The combined output becomes one feature matrix for the estimator. Grouping all steps in a pipeline lets cross-validation refit the mappings correctly within each training fold.
A category can also act as a proxy for sensitive or unstable context. A neighborhood may correlate with price but also reflect historical inequality. Removing an obvious sensitive column does not guarantee fairness when other columns encode similar information. The decision to use a categorical feature needs both predictive evaluation and an understanding of what decisions the model will influence.
Follow the code.
from sklearn.preprocessing import OneHotEncoder
colors = [["red"], ["blue"], ["green"], ["red"]]
encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
encoded = encoder.fit_transform(colors)
print(encoder.categories_)
print(encoded[0])
print(encoder.transform([["yellow"]]))Each inner list is one row with one categorical column. fit_transform first learns the categories and then returns numeric indicator rows. categories_ shows the learned order, which determines what each output position means. encoded[0] is the representation of red under that order. Yellow was not seen during fitting; handle_unknown='ignore' makes its indicator row all zeros instead of raising an error. All zeros can therefore mean an unknown category, which a downstream model must interpret cautiously.
The code does not imply red is greater or less than blue. It creates separate yes-or-no positions. In a full dataset, the encoder should be fit on training data only, and a pipeline should carry it with the model. A new category appearing frequently in live data may signal that the model's representation needs review.
What the result does not say.
A one-hot output is often sparse: most positions are zero. Sparse storage keeps only nonzero entries and can save memory. The example requests a dense array solely so the small result is easy to read.
For categories with real semantic hierarchy, such as country and city, separate indicators do not automatically teach that hierarchy. Feature design may express meaningful structure, but it should follow the task and avoid using future information.
One clear idea.
Encoding turns categories into features; the mapping and unknown-category policy are part of the model.
The ML cookbook
Complete, explained Python workflows sit alongside this reading course.