Lesson 54 · Mastering Pandas
How to Encode Categorical Variables in Pandas for Effective Data Preparation
In this lesson, we will learn how to work with categorical data in pandas and transform text labels into numerical codes using practical, real-world…
- CourseMastering Pandas
- Lesson54 of 44
- Video16 min
- FormatJupyter notebook · 14 code cells
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbEncoding Categorical Variables in Pandas#
In this lesson, we will learn how to work with categorical data in pandas and transform text labels into numerical codes using practical, real-world datasets.
By the end, you will be able to choose the right method for encoding, know when to use each, and avoid common pitfalls.
# Suppress warnings for clean outputs
import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings('ignore')
# Data setup (Titanic Dataset)
import pandas as pd
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
What Are Categorical Variables?#
Categorical variables are columns with a limited number of values, usually text labels.
For example, 'Sex' and 'Embarked' in Titanic are categorical because they use labels like 'male', 'female', 'S', 'C', or 'Q' instead of numbers.
# List object-type columns in Titanic
cat_cols = df.select_dtypes(include=['object']).columns
print(cat_cols.tolist())
# Count the unique values in each categorical column
for col in cat_cols:
print(f'{col}: {df[col].nunique()}')
Why Encode Categorical Data?#
Most machine learning models require numbers, not text. Encoding categorical variables turns words into digits, letting algorithms learn from them.
There are two main strategies: label encoding and one-hot encoding.
# Label encoding simple categories: 'Sex'
df['Sex_encoded'] = df['Sex'].astype('category').cat.codes
print(df[['Sex', 'Sex_encoded']].head(6))
# Map categories to custom values with a dictionary for 'Embarked'
embarked_map = {'S': 0, 'C': 1, 'Q': 2}
df['Embarked_encoded'] = df['Embarked'].map(embarked_map)
print(df[['Embarked', 'Embarked_encoded']].head(6))
One-Hot Encoding: When to Use It?#
One-hot encoding creates a separate column for each category, using 1 for present and 0 for absent.
It avoids implying order or priority, which is important for unordered categories.
# One-hot encode the 'Embarked' column
embarked_dummies = pd.get_dummies(df['Embarked'], prefix='Embarked')
print(embarked_dummies.head(6))
# Join one-hot encoded columns back to our DataFrame
df = pd.concat([df, embarked_dummies], axis=1)
print(df.head(3))
# Encoding multiple categorical variables at once
cols_to_encode = ['Sex', 'Embarked']
df_multi = pd.get_dummies(df, columns=cols_to_encode)
print(df_multi.head(3))
# Handle missing data before encoding
df['Embarked_fill'] = df['Embarked'].fillna('Unknown')
print(df[['Embarked', 'Embarked_fill']].head(8))
# One-hot encode including missing 'Unknown' level
embarked_full_dummies = pd.get_dummies(df['Embarked_fill'], prefix='Embarked')
print(embarked_full_dummies.head(8))
Categorical Data Type for Efficiency#
Pandas offers a special 'category' dtype which saves space and speeds up some operations. It is very useful for columns with a handful of distinct values.
# Convert 'Embarked' to pandas 'category' type
df['Embarked_category'] = df['Embarked'].astype('category')
print(df['Embarked_category'].dtype)
print(df['Embarked_category'].memory_usage(deep=True))
# Detect and encode ordinal categories
deck_map = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5, 'F':6, 'G':7, 'Unknown':0}
df['Deck'] = df['Cabin'].str[0].fillna('Unknown')
df['Deck_encoded'] = df['Deck'].map(deck_map)
print(df[['Deck', 'Deck_encoded']].drop_duplicates().sort_values('Deck_encoded'))
# Practice: Can you encode the 'Pclass' column as category?
df['Pclass_cat'] = df['Pclass'].astype('category')
print(df[['Pclass', 'Pclass_cat']].head(6))
Troubleshooting Encoding Problems#
- Nulls or spelling issues can break encoding.
- High-cardinality columns like 'Name' are not good for one-hot encoding.
- Recheck for unexpected new categories before predicting!
Recap#
- Label encoding is best for clear, ordered categories.
- One-hot encoding is right for unordered choices.
- Always handle missing data before encoding.
- The category dtype economizes memory.
Ready for a real challenge? Try encoding 'Ticket' using frequency or target-based methods!
Keep Learning and Connect!#
If this helped you out, remember to like and subscribe for more practical pandas walkthroughs. Leave a comment sharing how you use encoding in your own projects!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



