How to Convert Categorical Variables to Numbers in Python
In Python, categorical variables become numbers in two main ways: label encoding replaces each category with an integer, and one-hot encoding creates one binary column per category. The right choice depends on whether the variable has a real order (low, medium, high) or is purely nominal (city, color, plan). Choosing wrong creates magnitude relationships that do not exist in the data and quietly damages the model.
Why can't machine learning models read text columns directly?
Machine learning algorithms work with numbers: they compute distances, averages, coefficients, and split thresholds. A column holding values like 'New York' or 'Denver' has to be converted before it reaches the model.
The conversion itself is not the risk. The relationship it creates is. Map New York to 0, Austin to 1, and Denver to 2, and the algorithm now sees 0 < 1 < 2. It may conclude that Denver is somehow twice New York. For a nominal variable, that hierarchy does not exist.
So the first step is to classify each column: nominal when the categories only name groups, ordinal when there is a natural order between them.
- Nominal: city, marital status, color, plan type, acquisition channel.
- Ordinal: education level, risk band, income bracket, satisfaction rating.
- Binary: yes/no, active/inactive, a special case of nominal with two categories.
- Free text and identifiers (name, email, ID numbers) should not be encoded as categories at all.
How do you apply label encoding and ordinal encoding in Python?
Label encoding replaces each category with an integer. In scikit-learn, LabelEncoder does that for a single series, while OrdinalEncoder handles multiple columns and accepts the order you declare in categories.
On ordinal variables, state the order explicitly so the number reflects the real hierarchy. On nominal variables, label encoding is defensible only when the algorithm is tree-based, because splits on thresholds do not depend on the distance between codes. For linear models, SVM, and K-Means, the integer invents a scale that the data does not support.
- from sklearn.preprocessing import OrdinalEncoder
- OrdinalEncoder(categories=[['low','medium','high']]) — declared order, not alphabetical order.
- Note: scikit-learn's LabelEncoder is designed for the target vector (y), not for features.
- For features, prefer OrdinalEncoder inside a Pipeline so training and test data get the same mapping.
How do you apply one-hot encoding with Pandas, and when is it the right call?
One-hot encoding creates one binary column per category. In Pandas, pd.get_dummies(df, columns=['city']) does it in a single line. In scikit-learn, use OneHotEncoder with handle_unknown so an unseen category does not break the transform.
This is the default choice for nominal variables in linear regression, logistic regression, SVM, and K-Means, because it treats every category on equal footing and never implies an order.
The cost shows up on columns with many categories. A postal code or product ID column can produce hundreds of sparse columns, which raises dimensionality and makes the model harder to fit.
- pd.get_dummies(df, columns=['city'], drop_first=True) — drop_first removes one column to avoid redundancy.
- OneHotEncoder(handle_unknown='ignore') avoids errors when the test set contains a category not seen in training.
- Before encoding, group rare categories or review the frequency distribution.
- Check whether the output is float or bool and align the dtype with what the estimator expects.
Which technique prevents errors in each situation?
No technique is better in the abstract. What matters is the match between the variable type and the algorithm you plan to run. The table below sums up the practical decision.
The most common beginner mistake is applying label encoding to every categorical column because it is faster, without checking whether the variable has an order. The second most common is one-hot encoding high-cardinality columns and then wondering why training time exploded and performance dropped.
- Models based on linear combinations or distances need one-hot encoding for nominal variables.
- Trees, Random Forest, Gradient Boosting, XGBoost, and LightGBM handle integer codes well.
- Always apply the same encoding to train and test, with the same reference categories.
How do you keep encoding from leaking between train and test?
Encoding is part of preprocessing, so it has to be learned from training data only. Fitting an encoder on the full dataset, train plus test, lets category frequencies from the test set shape the feature space before evaluation.
Build the encoder inside a Pipeline, fit it on the training split, then transform the test split with that same object. Set handle_unknown='ignore' so categories that only appear in test become all-zero rows instead of errors.
After transforming, check column order, dtype, and shape. A silent mismatch between the training matrix and the test matrix is one of the least visible bugs in a machine learning project. Access to the course is permanent, so it is worth revisiting the preprocessing lessons whenever a pipeline behaves differently than expected.
- Fit on X_train only, then transform X_train and X_test with the same encoder.
- Keep the encoder as the first step of a Pipeline so cross-validation refits it on every fold.
- Column names and order should be identical before and after the transform.
- Save the fitted encoder alongside the model if the pipeline will run in production.
What do you do when a column has hundreds of categories?
One-hot encoding a column with hundreds of unique values creates a wide, mostly empty matrix. A frequent fix is to keep the most common categories and group the long tail into an 'other' bucket, based on frequency counts from the training set.
Tree-based models, including Random Forest, Gradient Boosting, XGBoost, and LightGBM, often consume integer codes directly, which avoids the column explosion. Frequency encoding and target encoding are alternatives, but target encoding needs an out-of-fold scheme or it leaks the target into the features.
The Python for Data Science and Analytics course at https://python.paanalytics.net/ covers data cleaning and preparation, Pandas, outlier detection, and feature selection before moving into these models, so the encoding decision sits inside a full workflow rather than as an isolated trick.
- Group rare categories by frequency and replace them with a single label.
- Try integer codes with tree-based models before building hundreds of dummy columns.
- If you use target encoding, compute it out-of-fold.
- Review feature selection after encoding: many dummy columns carry little signal.
Where does encoding fit in the full modeling workflow?
Encoding is one step between raw data and a model, and its effect only makes sense next to everything else: cleaning, outlier handling, feature selection, and validation. A column encoded correctly but evaluated on a leaking split still gives a misleading result.
The Python for Data Science and Analytics course runs from zero to advanced across three main modules — Basic, Intermediate, and Advanced — plus bonus modules, and requires no prior programming background. It covers IDE and Jupyter Notebook setup, NumPy and Pandas, user-defined functions, loops and conditionals, visualization, data cleaning and preparation, outlier detection, and then machine learning: linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation.
It closes with a final project that runs exploratory analysis and machine learning end to end. Lessons are recorded, watched at your own pace, with guided exercises, real market projects for a portfolio, a certificate of completion, an exclusive community for networking, and unlimited access with no expiration date. The price is R$ 470, payable in 12 installments of R$ 20.37 on the card, through the Hotmart checkout, which also accepts boleto. Enrollment starts at https://pay.hotmart.com/N45925741D?checkoutMode=10&sck=CTA_CARTAO&hideBillet=1.
- Encoding decisions belong inside the same pipeline as scaling and model fitting.
- Cross-validation should re-fit the encoder on each fold.
- A final project is where encoding, cleaning, and model choice get tested together.
| Technique | What it produces | Best suited for | Main risk if misapplied |
|---|---|---|---|
| Label / ordinal encoding | One integer column, ordered as declared | Ordinal features; nominal features fed to tree-based models | Linear and distance-based models read the integers as real distances |
| One-hot encoding | One binary column per category | Nominal features in linear regression, logistic regression, SVM, and K-Means | Column explosion on high-cardinality features |
| One-hot with drop_first | k−1 binary columns | Linear and logistic regression where redundancy hurts interpretation | Dropped category becomes the reference and must be remembered |
| Frequency or grouping of rare categories | Fewer, broader categories | Columns with hundreds of unique values | Loss of detail if the grouping threshold is poorly chosen |
Based on the documented behavior of pandas.get_dummies and scikit-learn's OrdinalEncoder and OneHotEncoder; no third-party benchmark data used.
Learn encoding, cleaning, and modeling in one end-to-end project
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Should I use pd.get_dummies or scikit-learn's OneHotEncoder?
pd.get_dummies is faster for exploration inside a notebook. OneHotEncoder is the better fit for anything reproducible, because it stores the category mapping, runs inside a Pipeline, and with handle_unknown='ignore' it survives categories that appear only at prediction time.
Does label encoding hurt tree-based models?
Usually not. Trees split on thresholds, so the distance between integer codes does not change the result the way it does for linear or distance-based models. Random Forest, Gradient Boosting, XGBoost, and LightGBM commonly consume integer codes directly.
How many categories are too many for one-hot encoding?
There is no universal cutoff. Watch the number of resulting columns, the sparsity of the matrix, and training time. When a column produces hundreds of dummy variables, grouping rare categories by frequency or switching to a tree-based model with integer codes is usually worth testing.
Do I need to scale features after encoding?
Binary dummy columns generally do not need scaling. Ordinal codes sometimes do, depending on the model. If you scale, fit the scaler on the training split only and keep it in the same Pipeline as the encoder.
Where can I learn this with Pandas and scikit-learn in one place?
The Python for Data Science and Analytics course at python.paanalytics.net covers data cleaning and preparation, Pandas, NumPy, visualization, feature selection, and cross-validation, then applies them in an end-to-end machine learning project. It runs from zero to advanced, needs no prior programming, includes exercises, a certificate, and permanent access, and costs R$ 470 in 12 installments of R$ 20.37 on the card via the Hotmart checkout at pay.hotmart.com/N45925741D.