Pandas pd.get_dummies() function
pd.get_dummies() is a function in the Pandas library used for **one-hot encoding of categorical variables (One-Hot Encoding)**. It converts categorical variables into binary (0/1) columns, with one column per category.
One-hot encoding is a common technique in machine learning preprocessing, because most algorithms cannot handle categorical data directly and need it converted into numeric form.
Word meaning: get_dummies Here "dummy" means "dummy variable", referring to the binary variables used in statistics and econometrics to represent categorical variables.
Basic syntax and parameters
pd.get_dummies() is a top-level function in the Pandas library used to convert categorical variables into one-hot encoded format.
Syntax format
pd.get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, drop_first=False, dtype=None)
Parameter Description
- Parameters:
data - Type: Series, DataFrame, or array-like object.
- Description: Data to one-hot encode. Usually a Series or DataFrame containing categorical variables.
- Parameters:
prefix - Type: string, list of strings, or dict.
- Description> The prefix for the generated new column names. If not specified, the original column name is used as the prefix.
- Parameters:
prefix_sep - Type: string.
- Description: The separator between the prefix and the category name. Defaults to the underscore
'_'。
- Parameters:
dummy_na - Type> boolean.
- Description> If
True, a separate column is also created for missing values (NaN). Defaults toFalse。
- Parameters:
columns - Type: list or None.
- Description: The column names to encode. If not specified, all columns of type object, category, or boolean are encoded.
- Parameters:
drop_first - Type: boolean.
- Description> If
True, the first column of each categorical variable is dropped to avoid multicollinearity. In models such as logistic regression, this avoids the dummy variable trap. Defaults toFalse。
Function description
- Return Value: Returns a DataFrame where each column corresponds to a category and the values are 0 or 1.
- effect: Converts categorical variables into numeric binary columns for easier processing by machine learning algorithms.
Example
Let us thoroughly master pd.get_dummies() through a series of examples from simple to complex.
Example 1: Basic usage - one-hot encode a Series
Example
import
pandas
as
pd
1. Create a Series containing categorical variables
colors
=
pd.
Series
(
[
'red'
,
'blue'
,
'green'
,
'red'
,
'green'
,
'blue'
]
)
(
"=== Original Series ==="
)
(
colors
)
2. One-hot encode using pd.get_dummies()
result
=
pd.
get_dummies
(
colors
)
(
"\n=== pd.get_dummies() one-hot encoding result ==="
)
(
result
)
Expected output:
=== 原始 Series ===
0 red
1 blue
2 green
3 red
4 green
5 blue
dtype: object
=== pd.get_dummies() 独热编码结果 ===
blue green red
0 False False True
1 True False False
2 False True False
3 False False True
4 False True False
5 True False False
Code analysis:
- The original Series contains three colors: red, blue, green.
- After one-hot encoding, each color becomes a column, using
True/Falseto indicate whether the row belongs to that category. - Each row has exactly one
True, corresponding to the original color value.
Example 2: Encode specified columns of a DataFrame
In data analysis, you usually only need to encode specific categorical columns, leaving numeric columns unchanged.
Example
import
pandas
as
pd
1. Create a DataFrame containing numeric and categorical variables
df
=
pd.
DataFrame
(
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'Diana'
]
,
'age'
:
[
25
,
30
,
35
,
28
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Beijing'
,
'Guangzhou'
]
,
'department'
:
[
'Sales'
,
'Engineering'
,
'Sales'
,
'HR'
]
}
)
(
"=== Original DataFrame ==="
)
(
df
)
2. One-hot encode the specified categorical columns
result
=
pd.
get_dummies
(
df
,
columns
=
[
'city'
,
'department'
]
)
(
"\n=== One-hot encode the city and department columns ==="
)
(
result
)
Expected output:
=== 原始 DataFrame ===
name age city department
0 Alice 25 Beijing Sales
1 Bob 30 Shanghai Engineering
2 Charlie 35 Beijing Sales
3 Diana 28 Guangzhou HR
=== 对 city 和 department 列进行独热编码 ===
name age city_Beijing city_Guangzhou city_Shanghai department_Engineering department_HR department_Sales
0 Alice 25 True False False False True
1 Bob 30 False False True True False
2 Charlie 35 True False False False True
3 Diana 28 False True False False False
Code analysis:
- Use
columnsThe parameter specifies that only thecityanddepartmentcolumns are encoded. - The numeric column
ageand the text columnnameremains unchanged. - The generated column names use the default underscore separator, such as
city_Beijing。
Example 3: Custom prefix and separator
You can use the prefix and prefix_sep The parameter customizes the names of the new columns.
< h2 class="example">Example
import
pandas
as
pd
1. Create a DataFrame
df
=
pd.
DataFrame
(
{
'color'
:
[
'red'
,
'blue'
,
'green'
,
'red'
]
,
'size'
:
[
'S'
,
'M'
,
'L'
,
'XL'
]
}
)
(
"=== Original DataFrame ==="
)
(
df
)
2. Use the prefix parameter to customize the prefix
result_prefix
=
pd.
get_dummies
(
df
,
prefix
=
[
'color'
,
'size'
]
)
(
"\n=== Use a custom prefix ==="
)
(
result_prefix
)
3. Use prefix_sep to customize the separator
result_sep
=
pd.
get_dummies
(
df
,
prefix
=
[
'color'
,
'size'
]
,
prefix_sep
=
'-'
)
(
"\n=== Use a custom separator '-' ==="
)
(
result_sep
)
Expected output:
=== 原始 DataFrame ===
color size
0 red S
1 blue M
2 green L
3 red XL
=== 使用自定义前缀 ===
color_blue color_green color_red size_L size_M size_S size_XL
0 False False True False False True False
1 True False False False True False False
2 False True False True False False False
3 False False True False False False True
=== 使用自定义分隔符 '-' ===
color-blue color-green color-red size-L ...
Code analysis:
prefix=['color', 'size']Specify different prefixes for different columns.prefix_sep='-'Changing the default underscore to a hyphen makes the new column names becomecolor-redthis form.
Example 4: Handling missing values and the drop_first parameter
Example
import
pandas
as
pd
import
numpy
as
np
1. Data containing missing values
df
=
pd.
DataFrame
(
{
'color'
:
[
'red'
,
'blue'
,
np.
nan
,
'red'
,
'green'
]
,
'size'
:
[
'S'
,
'M'
,
'L'
,
np.
nan
,
'XL'
]
}
)
(
"=== DataFrame with missing values ==="
)
(
df
)
2. By default, missing values are not handled
result_default
=
pd.
get_dummies
(
df
,
columns
=
[
'color'
]
)
(
"\n=== Missing values not handled by default ==="
)
(
result_default
)
3. dummy_na=True creates a separate column for missing values
result_na
=
pd.
get_dummies
(
df
,
columns
=
[
'color'
]
,
dummy_na
=
True
)
(
"\n=== dummy_na=True creates a column for missing values ==="
)
(
result_na
)
4. drop_first=True drops the first column to avoid multicollinearity
result_drop
=
pd.
get_dummies
(
df
,
columns
=
[
'size'
]
,
drop_first
=
True
)
(
"\n=== drop_first=True drops the first column ==="
)
(
result_drop
)
Expected output:
=== 包含缺失值的 DataFrame ===
color size
0 red S
1 blue M
2 NaN L
3 red NaN
4 green XL
=== 默认不处理缺失值 ===
size color_blue color_green color_red
0 S False False True
1 M True False False
2 L False False False
3 S False False True
4 XL False True False
=== dummy_na=True 为缺失值创建列 ===
size color_True color_blue color_green color_red
0 S False False False True
1 M False True False False
2 L True False False False
3 S False False False True
4 XL False False True False
=== drop_first=True 删除第一列 ===
color_blue color_green color_red
0 False False True
1 True False False
2 False False False
3 False False True
4 False True False
Code analysis:
dummy_na=True 为缺失值创建一个额外的列(本例中显示为 color_True 列)。
drop_first=True 删除每组的第一列(如 size_M 被删除),可以避免线性模型中的多重共线性问题。
提示: 独热编码会增加数据维度(每个类别一列),如果类别数量非常大,可能会导致维度灾难。在这种情况下,可以考虑使用标签编码(pd.factorize())或其他编码方法。
Pandas 常用函数
Common Pandas functions