Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.get_dummies() function

Pandas pd.get_dummies() function

Pandas Universal Functions Common Pandas functions


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

- Type: Series, DataFrame, or array-like object. - Description: Data to one-hot encode. Usually a Series or DataFrame containing categorical variables. - 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. - Type: string. - Description: The separator between the prefix and the category name. Defaults to the underscore '_'. - Type> boolean. - Description> If 'True', a separate column is also created for missing values (NaN). Defaults to 'False'. - Type: list or None. - Description: The column names to encode. If not specified, all columns of type object, category, or boolean are encoded. - 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 to 'False'.

Function description


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'

]

)

print

(

"=== Original Series ==="

)

print

(

colors

)

2. One-hot encode using pd.get_dummies()

result

=

pd.

get_dummies

(

colors

)

print

(

"\n=== pd.get_dummies() one-hot encoding result ==="

)

print

(

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:

  1. The original Series contains three colors: red, blue, green.
  2. After one-hot encoding, each color becomes a column, using True/False to indicate whether the row belongs to that category.
  3. 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'

]

}

)

print

(

"=== Original DataFrame ==="

)

print

(

df

)

2. One-hot encode the specified categorical columns

result

=

pd.

get_dummies

(

df

,

columns

=

[

'city'

,

'department'

]

)

print

(

"\n=== One-hot encode the city and department columns ==="

)

print

(

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:

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'

]

}

)

print

(

"=== Original DataFrame ==="

)

print

(

df

)

2. Use the prefix parameter to customize the prefix

result_prefix

=

pd.

get_dummies

(

df

,

prefix

=

[

'color'

,

'size'

]

)

print

(

"\n=== Use a custom prefix ==="

)

print

(

result_prefix

)

3. Use prefix_sep to customize the separator

result_sep

=

pd.

get_dummies

(

df

,

prefix

=

[

'color'

,

'size'

]

,

prefix_sep

=

'-'

)

print

(

"\n=== Use a custom separator '-' ==="

)

print

(

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:

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'

]

}

)

print

(

"=== DataFrame with missing values ==="

)

print

(

df

)

2. By default, missing values are not handled

result_default

=

pd.

get_dummies

(

df

,

columns

=

[

'color'

]

)

print

(

"\n=== Missing values not handled by default ==="

)

print

(

result_default

)

3. dummy_na=True creates a separate column for missing values

result_na

=

pd.

get_dummies

(

df

,

columns

=

[

'color'

]

,

dummy_na

=

True

)

print

(

"\n=== dummy_na=True creates a column for missing values ==="

)

print

(

result_na

)

4. drop_first=True drops the first column to avoid multicollinearity

result_drop

=

pd.

get_dummies

(

df

,

columns

=

[

'size'

]

,

drop_first

=

True

)

print

(

"\n=== drop_first=True drops the first column ==="

)

print

(

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 常用函数