Sub topic 5
Quick encoding with pandas get_dummies
This chapter assumes you can work with pandas DataFrames and Series, and that you know why a model needs numeric input and what a train/test split is. The earlier chapters explained why one-hot encoding exists. Here you will use pandas.get_dummies, the fastest way to produce one-hot columns, and learn where it stops being safe.
What get_dummies does
pd.get_dummies takes a Series or DataFrame and returns indicator columns, one per distinct value. In each row, exactly one indicator column is 1 and the others are 0.
import pandas as pd
df = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded) color_blue color_green color_red
0 0 0 1
1 0 1 0
2 1 0 0
3 0 1 0The original color column is replaced. The new names follow the pattern column_category, and the categories are sorted alphabetically. Each row has a single 1, so the row sums are all 1.
get_dummies is stateless. It does not remember which categories it saw, and it has no fit step. It looks at the data you pass and builds columns from that data alone. Most of the problems later in this chapter come from this property.
Which columns are encoded
If you call pd.get_dummies(df) without columns=, pandas encodes every column with dtype object, string, or category. Numeric and datetime columns pass through unchanged. The pass-through columns come first in the result, followed by the new indicator columns.
If you pass columns=[...], pandas encodes exactly those columns, whatever their dtype. This matters when a category is stored as an integer, such as a store ID or a postal code. Without columns=, it stays as a single numeric column, and a model will treat it as a quantity. This is the integer-coding problem from earlier in the tutorial. List such columns explicitly.
import pandas as pd
df = pd.DataFrame({
"store_id": [101, 102, 101, 103],
"price": [3.5, 4.0, 4.5, 5.0],
})
print(pd.get_dummies(df, columns=["store_id"], dtype=int))Parameters you will use
| Parameter | Default | Effect |
|---|---|---|
| `columns` | `None` | Names of columns to encode. If `None`, encodes object, string, and category columns. |
| `prefix` | column name | String, list, or dict giving the start of each new column name. |
| `prefix_sep` | `"_"` | Text placed between the prefix and the category. |
| `drop_first` | `False` | Drops the first category of each encoded column. |
| `dummy_na` | `False` | Adds an indicator column for missing values. |
| `dtype` | `bool` | Data type of the new columns. |
| `sparse` | `False` | Returns sparse columns, which save memory when most values are 0. |
The default dtype is bool in pandas 2.0 and later. Older versions used uint8. Many libraries accept booleans, but arithmetic and some exports behave better with numbers, so pass dtype=int or dtype=float explicitly. That also keeps your output the same across pandas versions.
Missing values
By default, a missing value gets 0 in every indicator column, so the row looks like "none of the above". Set dummy_na=True to give missing values their own column.
import pandas as pd
df = pd.DataFrame({
"size": ["small", "medium", None, "large"],
"price": [3.5, 4.0, 4.5, 5.0],
})
print(pd.get_dummies(df, columns=["size"], dummy_na=True, dtype=int)) price size_large size_medium size_small size_nan
0 3.5 0 0 1 0
1 4.0 0 1 0 0
2 4.5 0 0 0 1
3 5.0 1 0 0 0Row 2 now has a 1 in size_nan. Whether "missing" should count as its own category depends on your data. If missingness carries information, such as a customer who skipped an optional field, keep the column. If it does not, impute the value before encoding.
Dropping a column
drop_first=True removes the first category of each encoded column. This removes the exact redundancy where the indicators of one feature always sum to 1. That redundancy matters for unregularized linear models, and the chapter on redundant columns covers it. Tree-based models do not need it. One caution: with drop_first=True and dummy_na=True, the first category is still dropped, and the NaN column stays.
Prefixes
Use prefix to control column names, especially when you encode a Series, which would otherwise produce columns named only by the raw category.
import pandas as pd
s = pd.Series(["red", "green", "blue", "green"], name="color")
print(pd.get_dummies(s, prefix="color", prefix_sep="=", dtype=int).columns.tolist())This prints ['color=blue', 'color=green', 'color=red']. Distinct prefixes also prevent collisions when two columns share a category such as "other".
The train/test mismatch
Because get_dummies has no memory, encoding the training and test sets separately can produce different columns. A category that appears in only one set creates a column that the other set lacks.
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
train_enc = pd.get_dummies(train, dtype=int)
test_enc = pd.get_dummies(test, dtype=int)
print(train_enc.columns.tolist())
print(test_enc.columns.tolist())['color_blue', 'color_green', 'color_red']
['color_green', 'color_purple']The training set has three columns and the test set has two, and they are not the same two. A model fitted on the first cannot score the second. The matrix is also misaligned. Passing it to a model that only checks the number of columns would silently pair color_purple with the weights learned for color_blue.
Fix 1: reindex to the training columns
Treat the training columns as the reference. Align the test data to them, fill the gaps with 0, and discard the columns the model never saw.
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
train_enc = pd.get_dummies(train, dtype=int)
test_enc = pd.get_dummies(test, dtype=int).reindex(
columns=train_enc.columns, fill_value=0
)
print(test_enc) color_blue color_green color_red
0 0 1 0
1 0 0 0The unseen purple row is now all zeros, which means "none of the known categories". Missing columns are filled, and the extra color_purple column is dropped.
Fix 2: a fixed categorical dtype
You can also declare the allowed categories once and apply that definition to every dataset. A value outside the list becomes NaN, and NaN gives all zeros.
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
colors = pd.CategoricalDtype(["blue", "green", "red"])
train_enc = pd.get_dummies(train["color"].astype(colors), prefix="color", dtype=int)
test_enc = pd.get_dummies(test["color"].astype(colors), prefix="color", dtype=int)
print(train_enc.columns.tolist() == test_enc.columns.tolist())This prints True. get_dummies creates a column for every category in a categorical dtype, even one that does not occur in the data.
Where get_dummies fits
get_dummies suits exploration, quick baselines, and one-off analysis, where you want to see the encoded table immediately. It is a weak fit for a model you will deploy, for three reasons:
- It cannot be stored with the model. When a single new row arrives at prediction time,
get_dummiessees one category and returns one column, so you must rebuild the full column set by hand. - It cannot sit inside a scikit-learn
Pipelineor be cross-validated safely. Encoding before cross-validation uses categories from the validation folds. - It has no option for rare categories or unknown-value handling. You have to write them yourself, as in the reindex fix above.
The next chapter introduces OneHotEncoder, which remembers its categories and handles unseen values through a parameter. Use get_dummies when you want a quick look at the data. Use OneHotEncoder when the encoding has to be repeated reliably on new data.
Common errors
- Encoding the target. If you pass the whole DataFrame to
get_dummiesand the label column is a string, it gets encoded too. Separateyfirst. - Forgetting numeric categories. A category stored as an integer is skipped unless you list it in
columns=. - Encoding before splitting. The column set then depends on all rows, including test rows. Split first, then define the columns from the training set.
- Column explosion. A column with thousands of distinct values, such as user IDs, produces thousands of columns. Check
df[col].nunique()before encoding. Rare and high-cardinality values are handled in a later chapter. - Boolean output surprises. Boolean columns do not behave like integers in every downstream tool. Set
dtypeexplicitly.
Exercise
You run pd.get_dummies(train) and pd.get_dummies(test) separately on a feature with categories {"a", "b", "c"} in the training data and {"a", "d"} in the test data. What columns does each result have, and what single call makes the test matrix usable by a model trained on the training columns?
Show answer
The training result has columns x_a, x_b, x_c, where x is the original column name. The test result has x_a and x_d. Calling .reindex(columns=train_enc.columns, fill_value=0) on the encoded test data gives it the training columns. It adds x_b and x_c filled with 0 and drops x_d, so the row with "d" becomes all zeros.
Exercise
A DataFrame has a string column plan and an integer column region_code that identifies a sales region. You call pd.get_dummies(df, dtype=int). Which column is encoded, which is not, and how do you change the call to encode both?
Show answer
Only plan is encoded, because the default selects object, string, and category columns. region_code stays a single numeric column, so a model would treat region 30 as larger than region 10. Pass columns=["plan", "region_code"] to encode both.