get_dummies() (Pandas)

pd.get_dummies() turns a categorical column into one-hot encoded columns — a separate 0/1 (or True/False) indicator column for each distinct category. It is the standard way to prepare categories for machine learning.

Pandas

Most models need numbers, not text. get_dummies expands a category column with values like 'red', 'green', 'blue' into three boolean columns, each flagging whether a row had that value. This one-hot encoding avoids implying any false ordering between categories.

Key options: prefix tags the new column names so several encoded columns don't collide, drop_first=True removes one category to dodge the 'dummy variable trap' (perfect collinearity) in linear models, and dummy_na=True adds a column for missing values.

The inverse operation is pd.from_dummies, which collapses the indicator columns back to a single category column.

Syntax

pd.get_dummies(data, prefix=None, drop_first=False, dummy_na=False)

Examples

Python

import pandas as pd
print(pd.get_dummies(pd.Series(["a", "b", "a"])))

Output:

       a      b
0   True  False
1  False   True
2   True  False

Learn it in a lesson

See also

Back to the Dictionary