Course contentsShow
← Data Science
Lesson 640 of 2,14517. Categorical Predictors and InteractionsFree lesson

Encoding in Python with pandas

Using pd.get_dummies() and practical considerations for model-ready data preparation.

Encoding in Python with pandas

You'll learn how to convert categorical variables into numeric dummy variables using pd.get_dummies() for regression modeling.

The Core Idea

Once you understand dummy variable encoding conceptually, you need a practical tool to actually create those 0/1 columns from categorical data. In Python, pandas provides pd.get_dummies() — a function that automatically transforms categorical columns into model-ready dummy variables.

Think of pd.get_dummies() as a translator: it takes text categories like "Red", "Blue", "Green" and converts them into separate binary columns that regression algorithms can understand.

Basic Usage

import pandas as pd

# Sample data with a categorical variable
df = pd.DataFrame({
    'color': ['Red', 'Blue', 'Red', 'Green', 'Blue'],
    'price': [100, 150, 110, 130, 145]
})

# Create dummy variables
df_encoded = pd.get_dummies(df, columns=['color'])

This creates new columns: color_Red, color_Blue, color_Green with 0s and 1s.

Avoiding the Dummy Variable Trap

By default, pd.get_dummies() creates one column per category. To avoid perfect multicollinearity, drop one reference category:

df_encoded = pd.get_dummies(df, columns=['color'], drop_first=True)

Now you'll have color_Green and color_Red, with color_Blue as the implied reference.

Practical Considerations

  • Use drop_first=True for regression models to prevent the dummy variable trap
  • Keep the original data separate if you need category names later
  • For multiple categorical columns, list them all: columns=['color', 'size']
  • Column names automatically include the original variable name as a prefix

Key Takeaway: pd.get_dummies() with drop_first=True efficiently converts categorical variables into regression-ready dummy variables while automatically handling the reference category.