Pandas Get Dummies: Encode Categories

Turning category labels into indicator columns gives a pandas table one column for each category. pandas.get_dummies() creates those columns, using Boolean values by default or integers when you set dtype=int.

I’ll show how to encode selected columns and align training and test data.

TL;DR

pandas.get_dummies() creates indicator columns, with bool as the default dtype and integer output available through dtype=int.

  • Use columns= to choose fields and dtype=int for integer indicators.
  • Set dummy_na=True to represent missing values.
  • Reuse one category schema across training and test data.

What Is pandas get_dummies?

pandas.get_dummies() creates one indicator column per category. In my three-row city table, Delhi and Pune each receive a column.

Input citycity_Delhicity_Pune
Delhi10
Pune01

How to encode categorical columns step by step

Use pd.get_dummies() with explicit columns for mixed tables. I ran examples for selection, missing values, and aligned train/test fields with pandas 3.1.1.

Step 1: Encode selected DataFrame columns

Use columns= to select fields and prefix arguments to name the output.

ArgumentEffect in this exampleWhen to set it
columnsSelects city and channel, leaving amount untouched.Name fields explicitly when a table mixes categories and measurements.
prefixUses city and channel at the start of generated names.Use a string, list, or mapping.
prefix_sepSeparates each source name from its category label.Change the underscore separator if needed.
dtypeReturns integer indicators instead of the current bool default.Choose int when downstream code expects numeric 0/1 values.
import pandas as pd

orders = pd.DataFrame(
    {
        "city": ["Pune", "Delhi", "Pune"],
        "channel": ["web", "store", "web"],
        "amount": [120, 90, 140],
    }
)
encoded = pd.get_dummies(
    orders,
    columns=["city", "channel"],
    prefix=["city", "channel"],
    dtype=int,
)
print(encoded)

Save the code as basic_demo.py and run this exact command:

./.venv/bin/python basic_demo.py
arulius@askpython:~$ ./.venv/bin/python basic_demo.py
   amount  city_Delhi  city_Pune  channel_store  channel_web
0     120           0          1              0            1
1      90           1          0              1            0
2     140           0          1              0            1

Pandas indicator columns for city and sales channel in a three-row table
The encoded table keeps amount and adds one column per city and channel.

Step 2: Choose how to represent missing values

Without dummy_na=True, a missing value produces zeros in the indicator columns. I ran dummy_na=True and got region_nan for None.

Step 3: Keep train and test columns aligned

Separate calls can produce different columns. I used CategoricalDtype with blue, green, and red to align both schemas.

ApproachUse it whenBoundary to check
Shared CategoricalDtypeThe allowed category list is documented before the split.Values outside the list become missing.
Category allowed but absent in trainingThe feature column exists but is zero for every training row.The fitted model has no examples for that category’s effect.
Fitted OneHotEncoderA model pipeline must reuse categories learned from training.Pick how handle_unknown treats a new value.
Reindex encoded framesThe feature schema is known and already created.Reindex can discard test-only columns.

Handle missing values, errors, and train/test columns

A missing field name raises KeyError. I caused this by requesting colour from a DataFrame containing city.

import pandas as pd

orders = pd.DataFrame({"city": ["Pune", "Delhi"]})
try:
    pd.get_dummies(orders, columns=["colour"])
except KeyError as error:
    print(f"{type(error).__name__}: {error}")

Save as columns_error_demo.py and run the command:

./.venv/bin/python columns_error_demo.py
arulius@askpython:~$ ./.venv/bin/python columns_error_demo.py
KeyError: "None of [Index(['colour'], dtype='str')] are in the [columns]"

Pandas KeyError after get_dummies is given a column name that is absent
The error names colour, which is absent from the DataFrame.

Correct the spelling or inspect df.columns before calling get_dummies.

Choose the encoding approach to match the data and estimator:

CaseWhat happensChoice
Default dtypeNew indicator columns use bool.Set dtype=int for integer 0/1 output.
drop_first with an interceptOne category is omitted.Name the reference level. For penalized models, follow estimator guidance.
Numeric labelsNumeric fields stay unchanged by default.Convert to category only when numbers represent groups.
High cardinalityEach label adds a feature column.Check the number of distinct values first.
Several labels per cellA full string is one category.Use Series.str.get_dummies() for delimiter-separated labels.

Conclusion

Use pandas.get_dummies() when its output fits the next step. For model pipelines, define how categories are learned and reused.

FAQ

These short answers cover output details worth checking when moving from the example to a DataFrame.

Why does pandas get_dummies return True and False?

The default dtype for indicator columns is bool. Pass dtype=int for numeric 0 and 1 values.

Does get_dummies encode numeric columns by default?

No. With columns=None, pandas selects object, string, or category fields. Include a numeric field in columns= only when it represents category labels.

Can I turn dummy columns back into categories?

Use pandas.from_dummies(). Set default_category when an omitted reference category appears as an all-zero row.

Arulius Savio
Arulius Savio
Articles: 56