Sub topic 5
Quick encoding with pandas get_dummies
This chapter assumes you know basic Python and pandas DataFrames, and that you understand why models need numeric input and why one-hot columns beat arbitrary integer codes. Here you will use pd.get_dummies to encode a column, and you will see where it stops being safe to use.
What get_dummies does
pandas.get_dummies takes a DataFrame, finds the categorical columns you name, and replaces each one with a set of indicator columns. Each indicator column is named column_category and holds 1 where the row has that category and 0 elsewhere.
import pandas as pd
df = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded)The output has three columns: color_blue, color_green and color_red. The original color column is gone. Categories are sorted alphabetically, so the column order does not follow the order of first appearance.
Options you will use often
columns=[...]limits encoding to the named columns. Without it, pandas encodes every column with object, string or category dtype. Numeric columns are left alone.dtype=intreturns 0 and 1. Recent pandas versions returnTrueandFalseby default, which some libraries handle poorly.prefixandprefix_sepchange the column names.drop_first=Truedrops the first category of each column to remove redundancy. Thedropoption ofOneHotEncodercovers the same idea in a later chapter.dummy_na=Trueadds a column that marks missing values. By default, a missing value gives a row of all zeros.
import pandas as pd
df = pd.DataFrame({
"city": ["Paris", "Berlin", None, "Paris"],
"age": [25, 32, 47, 51],
})
print(pd.get_dummies(df, columns=["city"], dummy_na=True, dtype=int))The age column passes through unchanged. The result has city_Berlin, city_Paris and city_nan.
The limitation: it has no memory
get_dummies is a plain function. It looks only at the DataFrame you give it and keeps no record of the categories it saw. That causes two common errors when you use it for modeling.
- Mismatched columns. If you call it separately on training and test data, each call builds columns from its own values. A category present in only one set produces a column the other set lacks, and the model receives a different number of features, or the same columns in a different order.
- Information from the wrong data. Building the category list from the full dataset before splitting lets test-set information shape your features. The next chapters cover this as leakage.
The example below shows the mismatch.
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue"]})
test = pd.DataFrame({"color": ["green", "purple"]})
train_enc = pd.get_dummies(train, dtype=int)
test_enc = pd.get_dummies(test, dtype=int)
print(list(train_enc.columns))
print(list(test_enc.columns))The training columns are color_blue, color_green, color_red. The test columns are color_green, color_purple. A model trained on the first set cannot score the second.
You can patch this with reindex, which forces the test columns to match the training columns.
test_aligned = test_enc.reindex(columns=train_enc.columns, fill_value=0)
print(test_aligned)Now purple is dropped and the test frame has the same columns as the training frame. This works, but you must remember to do it on every batch of new data. A fitted encoder does this for you.
When to use it
| Situation | Use get_dummies? |
|---|---|
| Exploring data in a notebook | Yes |
| Quick analysis with no train/test split | Yes |
| A model that will score new data later | No, use `OneHotEncoder` |
| Encoding inside a `Pipeline` | No, use `OneHotEncoder` |
Exercise
You call pd.get_dummies on a training set and again on a test set. The test set has a category the training set never contained. What goes wrong, and how can you repair the test frame by hand?
Show answer
The test frame gets an extra column that the training frame lacks, so the feature sets no longer match the trained model. You can call reindex(columns=trainencoded.columns, fillvalue=0) on the encoded test frame. This drops the unknown column and fills any missing ones with 0. A fitted OneHotEncoder with handle_unknown="ignore" handles this automatically.