Learning Guides
Categorical Data in Python: Complete Guide
Quick answer: Learn how to handle categorical data in Python with Pandas, including nominal vs ordinal data, one-hot encoding, label encoding, and the category dtype.
What is Categorical Data?
Categorical data represents values that fall into a limited, fixed set of categories, such as colour, city or customer segment, rather than continuous numbers.
Nominal vs Ordinal Data
| Nominal | Ordinal |
|---|---|
| Categories have no natural order | Categories have a meaningful order |
| Example: city, colour, gender | Example: education level, satisfaction rating |
The category dtype in Pandas
import pandas as pd
df = pd.DataFrame({'city': ['Nagpur', 'Pune', 'Nagpur', 'Mumbai']})
df['city'] = df['city'].astype('category')
print(df['city'].cat.categories) # Index(['Mumbai', 'Nagpur', 'Pune'])
Converting a text column to category can significantly reduce memory usage when the column has many repeated values, and speeds up certain operations like grouping.
One-Hot Encoding
One-hot encoding converts a categorical column into multiple binary columns, one per category, which most Machine Learning algorithms require since they cannot work directly with text labels.
df_encoded = pd.get_dummies(df, columns=['city'])
print(df_encoded)
This works well for nominal data with a manageable number of categories, but can create too many columns if a category has hundreds of unique values.
Label Encoding
Label encoding assigns each category an integer, which is more compact but introduces an artificial numeric order that can mislead a model if the data is genuinely nominal.
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
df['city_encoded'] = encoder.fit_transform(df['city'])
Label encoding is more appropriate for ordinal data, where the assigned numeric order can be made to reflect the real underlying order of the categories.
Encoding Ordinal Data Correctly
from pandas.api.types import CategoricalDtype
grade_order = CategoricalDtype(categories=['Low', 'Medium', 'High'], ordered=True)
df['satisfaction'] = df['satisfaction'].astype(grade_order)
Common Interview Questions
What is the difference between one-hot encoding and label encoding?
One-hot encoding creates a separate binary column per category with no implied order, suited to nominal data. Label encoding assigns a single integer per category, which is more appropriate for ordinal data where an order genuinely exists.
Why is label encoding risky for nominal categorical data?
It introduces an artificial numeric relationship, such as implying city A is somehow less than city B, which some models may misinterpret as meaningful when it is not.
FAQ
Frequently Asked Questions
What is the difference between nominal and ordinal categorical data?
Nominal data has categories with no natural order, such as city or colour. Ordinal data has categories with a meaningful order, such as education level or a satisfaction rating.
What is one-hot encoding?
A technique that converts a categorical column into multiple binary columns, one per category, so a model can work with the data numerically without implying a false order.
When should you use label encoding instead of one-hot encoding?
Label encoding is more appropriate for ordinal data, where the assigned numeric order can reflect a genuine underlying order among the categories.
Why convert a column to Pandas' category dtype?
It reduces memory usage for columns with many repeated values and can speed up operations like grouping and sorting.
Keep Reading
Related Articles
Learning Guides
INNER JOIN in SQL with Examples: Complete Beginner's Guide
Learn INNER JOIN in SQL with practical examples, syntax, interview questions, and real-world use cases. A complete beginner-friendly SQL JOI
Learning Guides
OUTER JOIN in SQL: Complete Guide with Examples for Beginners
Master OUTER JOIN in SQL with practical examples and real-world scenarios. Learn LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, syntax, use cases,
Learning Guides
Multi-Row Functions in SQL: Complete Guide with Examples
Learn multi-row (aggregate) functions in SQL including SUM, AVG, COUNT, MIN, MAX, GROUP BY and HAVING, with practical examples, NULL handlin