Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to Convert Categorical Variables to Numbers in Python

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.

Topics: encoding, variáveis categóricas, one-hot

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.

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.

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.

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.

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.

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.

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.

TechniqueWhat it producesBest suited forMain risk if misapplied
Label / ordinal encodingOne integer column, ordered as declaredOrdinal features; nominal features fed to tree-based modelsLinear and distance-based models read the integers as real distances
One-hot encodingOne binary column per categoryNominal features in linear regression, logistic regression, SVM, and K-MeansColumn explosion on high-cardinality features
One-hot with drop_firstk−1 binary columnsLinear and logistic regression where redundancy hurts interpretationDropped category becomes the reference and must be remembered
Frequency or grouping of rare categoriesFewer, broader categoriesColumns with hundreds of unique valuesLoss 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 site

Frequently 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.

Ler em português →