Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 30

Categorical Data Encoding

Recommended resources

Hello! Welcome to our next lesson on data preparation.

In the previous lesson, we tackled how to handle numerical features by scaling them with StandardScaler and MinMaxScaler. You learned the importance of putting all numerical features on a common scale to ensure machine learning algorithms perform effectively.

However, datasets are rarely composed of just numbers. They often contain categorical data—features represented by text labels, like 'color', 'city', or 'product_category'. Since machine learning models are fundamentally mathematical, they can't work directly with text.

This lesson bridges that gap. Our goal is to encode categorical variables using one-hot and label encoding. We will explore two primary techniques to convert these text-based categories into the numerical format that models require. Understanding how and when to use each method is a critical step in building robust machine learning models.

1. Understanding Categorical Data

First, let's clarify what we're working with. Categorical data represents discrete, named groups. It's crucial to distinguish between its two main types, as this distinction dictates which encoding strategy you should use.

  • Nominal Data: The categories have no intrinsic order or ranking. For example, the township column in a housing dataset ('Monroeville', 'West Windsor', 'Robinsville') is nominal. There's no inherent order suggesting one town is "greater" or "less than" another.
  • Ordinal Data: The categories have a meaningful order or rank. For example, a feature for education level ('High School', 'Bachelors', 'Masters', 'PhD') is ordinal because there's a clear progression.

To dive deeper into this distinction and see why simply assigning numbers (e.g., Monroeville=0, West Windsor=1) is problematic for nominal data, please watch the beginning of the following video.

Machine Learning Tutorial Python - 6: Dummy Variables & One Hot Encoding

This video from codebasics clearly explains the difference between nominal and ordinal variables and illustrates why a simple integer mapping can mislead a machine learning model.

Watch from the beginning to 02:52. Pay close attention to the example of townships and the issues that arise from assigning simple integer values.

This tutorial from DataCamp also provides clear, concise definitions of nominal and ordinal data that you can use as a reference.

Handling Machine Learning Categorical Data with Python ...

To solidify your understanding, please read the first part of this DataCamp article.

Read the introductory section and the subsections on 'Nominal data' and 'Ordinal data'.


2. Label Encoding for Ordinal Data

As you just saw, naively assigning numbers to nominal categories can be a bad idea. However, what if the data is ordinal? In that case, converting categories to integers is the right approach. This technique is called Label Encoding or Ordinal Encoding.

For example, if you have a feature size with categories ['small', 'medium', 'large'], encoding them as [0, 1, 2] preserves the inherent order.

Scikit-learn provides the OrdinalEncoder for this purpose. It maps each category to an integer. By default, it determines the order alphabetically, but you can—and should—provide the correct order for your ordinal features to ensure the encoding is meaningful.

Let's look at how this works in practice.

Encoding of categorical variables — Scikit-learn course

This section from the official scikit-learn course demonstrates how to use OrdinalEncoder and discusses its main assumption: that the encoded integers represent a meaningful order.

Read the section titled 'Encoding ordinal categories'. Observe how the encoder transforms the 'education' column and note the warning about applying this method to non-ordinal data.

The key takeaway is that Label/Ordinal Encoding should primarily be used for features where the categories have a clear, logical ranking. Using it on nominal data can cause a model to learn a false relationship (e.g., that 'Blue' is greater than 'Green') and make incorrect predictions.


3. One-Hot Encoding for Nominal Data

So, how do we handle nominal data? The most common and effective technique is One-Hot Encoding.

The idea is to create a new binary (0 or 1) column for each unique category in the original feature. For each row, a '1' is placed in the column corresponding to its category, and '0's are placed in all other new columns.

This avoids the problem of artificial ordering because no single column contains a range of values. Each category is represented by its own on/off switch.

Comparison of Label Encoding and One-Hot Encoding
This image visually contrasts the two encoding methods. Label Encoding transforms the 'Color' feature into a single column with numerical values (0, 1, 2). One-Hot Encoding expands it into three new binary columns, one for each color, eliminating any implied order.

For a crystal-clear conceptual explanation, the following StatQuest video is excellent.

One-Hot, Label, Target and K-Fold Target Encoding, Clearly Explained!!!

Josh Starmer provides one of the best explanations of the one-hot encoding concept.

Watch from 01:33 to 03:01. Notice how the single 'favorite color' column is transformed into three distinct binary columns.

Practical Implementation

There are two main ways to perform one-hot encoding in Python.

A. Using Pandas get_dummies()

This is the quickest way to perform one-hot encoding. It's a simple function that takes a DataFrame or Series and returns a new DataFrame with the encoded columns.

Machine Learning Tutorial Python - 6: Dummy Variables & One Hot Encoding

Let's return to the codebasics video for a practical demonstration of pd.get_dummies().

Watch from 03:35 to 05:38. See how pd.get_dummies() is used and then concatenated with the original DataFrame.

The Dummy Variable Trap

When you one-hot encode a feature with k categories, you get k new columns. However, one of these columns is perfectly predictable from the others. For example, if you know a person is not from 'West Windsor' and not from 'Robinsville', they must be from 'Monroeville'. This redundancy is called multicollinearity and can be problematic for some models, particularly linear ones.

To avoid this "dummy variable trap," a common practice is to drop one of the one-hot encoded columns. The model can infer the dropped category when all other binary columns are 0.

Machine Learning Tutorial Python - 6: Dummy Variables & One Hot Encoding

The codebasics video explains this concept and how to manually handle it.

Watch from 05:38 to 07:32. Understand why dropping one dummy variable is important. You can achieve this in pandas by using pd.get_dummies(df, drop_first=True).

B. Using Scikit-learn OneHotEncoder

While get_dummies is convenient for quick analysis, OneHotEncoder from scikit-learn is the preferred method within a machine learning pipeline.

Why? The key reason is consistency. Just like with StandardScaler from our last lesson, you need to fit the encoder only on your training data and then transform both your training and test sets. OneHotEncoder allows you to do this, preventing data leakage. It learns the categories from the training set and can then handle new data consistently. It can also be configured to gracefully handle categories that appear in the test set but were not in the training set.

This makes OneHotEncoder much more robust for building and deploying models.

Encoding of categorical variables — Scikit-learn course

The scikit-learn course provides a detailed guide on using OneHotEncoder and highlights some of its powerful parameters.

First, read the section 'Encoding nominal categories (without assuming any order)' to see OneHotEncoder in action. Then, jump to the subsection under 'Evaluate our predictive pipeline' that discusses handling rare categories. Pay special attention to the handle_unknown='ignore' parameter, which is a powerful tool for real-world scenarios.

To automatically avoid the dummy variable trap with OneHotEncoder, you can initialize it like this: OneHotEncoder(drop='first').


4. Choosing the Right Encoding Strategy

You now have two main tools in your toolbox. Here’s a summary of when to use each:

Situation Recommended Encoder Why?
Ordinal Data (e.g., 'low', 'medium', 'high') OrdinalEncoder Preserves the meaningful order of the categories.
Nominal Data (e.g., 'red', 'green', 'blue') for linear models OneHotEncoder Avoids creating a false sense of order that would confuse the model.
Nominal Data for tree-based models (e.g., Decision Trees, Random Forests) Either OneHotEncoder or OrdinalEncoder Tree-based models are less sensitive to the ordering issue, so OrdinalEncoder can sometimes be used as a simpler, more memory-efficient option. However, OneHotEncoder is generally a safer bet.

This article provides an excellent summary of these points.

Encoding of categorical variables — Scikit-learn course

This section of the scikit-learn course offers clear guidance on selecting an encoding strategy based on the data and the model you plan to use.

Read the section 'Choosing an encoding strategy'. It provides a concise and practical rule of thumb for when to use each encoder.

Test your understanding!

You are given a dataset to predict customer churn. It contains a feature named subscription_tier with three possible values: 'Basic', 'Premium', and 'Ultimate'. You are planning to train a Logistic Regression model (which is a linear model).

Which encoding strategy is most appropriate for the subscription_tier feature and why?

Show answer

The most appropriate strategy is Ordinal Encoding.

Reasoning:

  1. The subscription_tier feature is ordinal because there is a clear, meaningful order: 'Basic' < 'Premium' < 'Ultimate'.
  2. Using OrdinalEncoder (e.g., mapping them to 0, 1, 2) would capture this inherent ranking, providing a valuable signal to the model.
  3. While OneHotEncoder would also work and is safe for linear models, it would not explicitly capture the ordered relationship between the tiers. It would treat them as independent categories, losing potentially useful information.

Conclusion

Congratulations! You've just learned another essential data preprocessing skill. You now know how to convert non-numeric categorical data into a format that machine learning models can understand, a process you'll perform in nearly every project.

Key Takeaways:

  • Machine learning models require all input features to be numeric.
  • Label/Ordinal Encoding converts categories into integers. It's best suited for ordinal data where a natural order exists.
  • One-Hot Encoding creates new binary columns for each category. It's the standard choice for nominal data to avoid imposing a false order.
  • Be mindful of the dummy variable trap (multicollinearity) when using one-hot encoding and use parameters like drop_first=True (pandas) or drop='first' (scikit-learn) to mitigate it.
  • For building robust ML pipelines, prefer scikit-learn's OneHotEncoder and OrdinalEncoder over pandas' get_dummies because they can be saved and applied consistently across training and test data.

Preview of the Next Lesson:

We have now covered preprocessing for both numerical and categorical features. However, sometimes the distribution of a numerical feature itself can be problematic. In our next lesson, we will explore how to handle skewed data distributions using mathematical transformations like the log transform, which can help certain models perform better.