Feature encoding
Prepare categorical features for a machine-learning model.
Pandas · Function
Converts categorical values into 0/1 indicator columns. DataFrame inputs can selectively encode columns and retain other columns.
pd.get_dummies converts categorical values into indicator columns containing 0 or 1. For a DataFrame, selected columns—or, when columns is omitted, columns with object, string, or category dtype—are expanded and named using the source column and category value.
pandas.get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)| Name | Type | Description |
|---|---|---|
data | array-like, Series, or DataFrame | Array-like, Series, or DataFrame containing the data to encode. |
prefix | str, list of str, or dict of str, default None | String, list of strings, or mapping used to prefix DataFrame column names; default None. |
prefix_sep | str, default '_' | Separator used between a prefix and category value; default '_'. |
dummy_na | bool, default False | Whether to add an indicator for missing values; default False. |
columns | list-like, default None | DataFrame column names to encode; default None. |
sparse | bool, default False | Whether generated columns use SparseArray backing; default False. |
drop_first | bool, default False | Whether to omit the first category level; default False. |
dtype | dtype, default None | Data type for the generated indicators; default None. |
DataFrame of dummy-coded data.
import pandas as pd
df = pd.DataFrame({"color": ["red", "blue", "red"], "value": [1, 2, 3]})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded)Encodes the selected categorical column as integer indicator columns while retaining the numeric column.
Prepare categorical features for a machine-learning model.
Turn labeled categories into analysis-ready indicator columns.
Represent missingness explicitly as a model feature.
It creates one indicator column for each distinct category in the input. For DataFrame input, generated names combine the original column name with the category value.
Follow-up: How would you avoid encoding every eligible column? Pass an explicit list of column names through columns.
By default, columns is None, so object, string, and category columns are converted. Supplying columns restricts encoding to the named DataFrame columns.
Follow-up: What happens to columns not listed in columns? They remain in the returned DataFrame unchanged.
drop_first=True removes the first category level, producing k−1 indicator columns for k levels. This can remove a redundant reference category in models.
Follow-up: How are missing values handled when dummy_na=True? A separate indicator column is added for missing values.
pandas.from_dummiespandas.Categoricalpandas.Series.str.get_dummies