One-Hot Encoding with get_dummies
Reviewed & published by Brayan K
One-hot encoding is the technique of replacing one text category column with several 0/1 indicator columns — one per category — so that machine learning models can read your categorical data as plain numbers without inventing a false order.
Part of the free Pandas course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You will use pd.get_dummies() with columns=, drop_first=, and dtype=int, understand why models need it, and reverse the process with pd.from_dummies().
What You'll Learn in This Lesson
- Why models need numeric, unordered categories
- Turn a column into 0/1 columns with get_dummies
- Target specific columns with columns=[...]
- Avoid the dummy trap with drop_first=True
- Get clean integers with dtype=int
- Reverse the encoding with from_dummies
1 Why One-Hot, and the Basic Call
Suppose a color column holds "red", "green", "blue". If you naively map them to 0, 1, 2 the model thinks blue (2) is twice green (1) — a meaning that does not exist. One-hot encoding instead creates a separate column per category that is 1 when the row matches and 0 otherwise, so no fake ordering sneaks in.
import pandas as pd
df = pd.DataFrame({"color": ["red", "green", "blue"]})
pd.get_dummies(df, dtype=int)
# color_blue color_green color_red
# 0 0 0 1
# 1 0 1 0
# 2 1 0 0import pandas as pd
df = pd.DataFrame({
"size": ["S", "M", "L", "M"],
"price": [10, 12, 15, 12],
})
# Expand the text column into 0/1 columns
encoded = pd.get_dummies(df, dtype=int)
print(encoded)
# ✅ Expected output:
# price size_L size_M size_S
# 0 10 0 0 1
# 1 12 0 1 0
# 2 15 1 0 0
# 3 12 0 1 02 columns=, drop_first= and dtype=
Use columns=[...] to encode only the columns you name and leave the rest alone. Use drop_first=True to drop the first indicator column — it is redundant because "all zeros" already identifies that category, and keeping it can confuse regression models (the dummy variable trap).
df = pd.DataFrame({"city": ["NYC", "LA", "NYC"],
"n": [1, 2, 3]})
# only encode "city", drop the first level, integer output
pd.get_dummies(df, columns=["city"], drop_first=True, dtype=int)
# n city_NYC
# 0 1 1
# 1 2 0
# 2 3 1import pandas as pd
df = pd.DataFrame({
"city": ["NYC", "LA", "SF", "LA"],
"rooms": [2, 1, 3, 2],
})
# Encode only "city", drop the first level to avoid the dummy trap
out = pd.get_dummies(df, columns=["city"], drop_first=True, dtype=int)
print(out)
# ✅ Expected output:
# rooms city_NYC city_SF
# 0 2 1 0
# 1 1 0 0
# 2 3 0 1
# 3 2 0 03 The Round Trip — from_dummies()
Once you are done processing, you often want the readable label back. pd.from_dummies() collapses the one-hot columns into a single category column again. It needs a sep= so it knows where the prefix ends, matching the underscore that get_dummies inserted.
df = pd.DataFrame({"g": ["a", "b", "a"]})
encoded = pd.get_dummies(df, dtype=int)
# columns: g_a, g_b
pd.from_dummies(encoded, sep="_")
# g
# 0 a
# 1 b
# 2 aimport pandas as pd
df = pd.DataFrame({"animal": ["dog", "cat", "dog", "bird"]})
# Encode...
enc = pd.get_dummies(df, dtype=int)
print(enc)
# animal_bird animal_cat animal_dog
# 0 0 0 1
# 1 0 1 0
# 2 0 0 1
# 3 1 0 0
# ...then decode back to one column
print(pd.from_dummies(enc, sep="_"))
# ✅ Expected output:
# animal_bird animal_cat animal_dog
# 0 0 0 1
# 1 0 1 0
# 2 0 0 1
# 3 1 0 0
# animal
# 0 dog
# 1 cat
# 2 dog
# 3 birdimport pandas as pd
df = pd.DataFrame({
"fruit": ["apple", "pear", "apple", "kiwi"],
"qty": [3, 1, 5, 2],
})
# 🎯 YOUR TURN:
# One-hot encode ONLY the "fruit" column and return integers (0/1),
# not True/False. Fill in the ___ with the right argument.
out = pd.get_dummies(df, columns=["fruit"], dtype=___)
print(out)
# Expected output:
# qty fruit_apple fruit_kiwi fruit_pear
# 0 3 1 0 0
# 1 1 0 0 1
# 2 5 1 0 0
# 3 2 0 1 0! Common Errors (And How to Fix Them)
❌ Surprised by True/False columns
Modern pandas returns booleans by default, which can break later math:
pd.get_dummies(df) # ❌ columns are True/False✅ Fix: ask for integers explicitly:
pd.get_dummies(df, dtype=int) # ✅ clean 0 and 1❌ from_dummies fails on a drop_first encoding
enc = pd.get_dummies(s, drop_first=True)
pd.from_dummies(enc, sep="_") # ❌ all-zero rows have no category✅ Fix: decode the full encoding, or give a default:
pd.from_dummies(enc, sep="_", default_category="first") # ✅🎯 Mini Challenge: Prepare Features for a Model
Turn a tiny housing table into a numeric feature matrix.
- One-hot encode neighborhood and style
- Drop the first level of each to avoid the dummy trap
- Return integer columns and keep the numeric price
import pandas as pd
df = pd.DataFrame({
"neighborhood": ["north", "south", "north"],
"style": ["ranch", "ranch", "colonial"],
"price": [300, 250, 410],
})
features = pd.get_dummies(
df,
columns=["neighborhood", "style"],
drop_first=True,
dtype=int,
)
print(features)
# ✅ Expected output:
# price neighborhood_south style_ranch
# 0 300 0 1
# 1 250 1 1
# 2 410 0 0❓ Frequently Asked Questions
Lesson complete — your categories are model-ready!
You can expand text columns into 0/1 indicators with get_dummies, target specific columns, drop the redundant level, force integers with dtype=int, and reverse it all with from_dummies.
Practice quiz
What does one-hot encoding do to a text category column?
- Replaces it with a separate 0/1 column per category
- Deletes it
- Maps it to 0, 1, 2 in order
- Sorts it alphabetically
Answer: Replaces it with a separate 0/1 column per category. Each category gets its own indicator column that is 1 when the row matches, else 0.
Why is mapping categories to 0, 1, 2 a problem for many models?
- It uses too much memory
- It implies a false ordering between categories
- It is slower to compute
- It cannot be reversed
Answer: It implies a false ordering between categories. Models treat numbers as ordered, so 0/1/2 wrongly implies one category is 'greater'.
In each row of a one-hot encoding, how many indicator columns are 'hot' (1)?
- All of them
- None
- Exactly one
- Two
Answer: Exactly one. Exactly one column is 1 per row, which is why it is called one-hot.
What does the columns=[...] argument of get_dummies do?
- Renames the output columns
- Sets the column order
- Drops those columns
- Encodes only the columns you name
Answer: Encodes only the columns you name. columns=[...] limits encoding to the listed columns and leaves the rest alone.
What does drop_first=True do?
- Drops the first redundant indicator column
- Removes the first row
- Sorts categories
- Keeps only the first category
Answer: Drops the first redundant indicator column. It removes one redundant column to avoid the dummy variable trap in regression.
Why pass dtype=int to get_dummies in modern pandas?
- To sort the output
- Modern pandas returns True/False by default; dtype=int gives clean 0 and 1
- To reduce the number of columns
- It is required or it errors
Answer: Modern pandas returns True/False by default; dtype=int gives clean 0 and 1. By default pandas returns booleans; dtype=int produces integer 0/1 columns.
Which function reverses one-hot encoding back to a single column?
- pd.melt()
- pd.undummy()
- pd.from_dummies()
- pd.decode()
Answer: pd.from_dummies(). pd.from_dummies() reconstructs the original categorical column.
Which kind of model usually does NOT need drop_first=True?
- Linear regression
- Logistic regression
- Models that assume no multicollinearity
- Tree-based models
Answer: Tree-based models. Tree models do not suffer the dummy trap, so you usually keep every column there.
For get_dummies on color values red, green, blue with dtype=int, what is the sum across the new columns in any single row?
- 1
- 0
- 2
- 3
Answer: 1. Exactly one indicator is 1 per row, so the row sum is 1.
Why can from_dummies fail on a drop_first encoding?
- It needs more than one row
- An all-zeros row has no category to recover
- It only works with strings
- It needs a numeric index
Answer: An all-zeros row has no category to recover. With the first column dropped, an all-zeros row is ambiguous unless you give default_category.
Continue this course
- Previous: Binning Continuous Data: cut & qcut
- Next: Rolling & Expanding Windows — Compute moving averages and running totals with rolling, expanding, and ewm
- Quick reference: Pandas cheat sheet
Frequently asked questions
Why do machine learning models need one-hot encoding instead of plain text?
Most models only accept numbers, and they treat numbers as ordered quantities. If you map red=0, green=1, blue=2, the model wrongly assumes blue is 'greater than' red. One-hot encoding gives each category its own 0/1 column, so no false ordering is implied and every category is treated independently.
What does drop_first=True do and when should I use it?
drop_first=True removes the first category column because it is redundant — if all the other category columns are 0, the dropped one must be 1. This avoids the 'dummy variable trap' (perfect multicollinearity) that hurts linear and logistic regression. Tree-based models do not need it, so it is optional there.
Why pass dtype=int to get_dummies?
Modern pandas returns boolean True/False columns by default. Passing dtype=int gives you clean 0 and 1 integers instead, which many libraries and exports expect and which are easier to read in printed output.
Can I reverse one-hot encoding back to a single column?
Yes. pd.from_dummies() takes the one-hot columns and reconstructs the original categorical column. It is the round-trip partner of get_dummies and is handy when you need to recover the human-readable labels after processing.