Pandas Get Dummies

虚拟变量是用于编码分类数据的数值表示。

虚拟变量显示二元值,仅01

对于某些数据,每个项目只能属于一个类别。例如,汽车可以是红色蓝色,但不能同时是两者。

但是,某些数据可以属于多个类别。例如一部电影既是动作片又是喜剧片

在这两种情况下,Pandas 中 get_dummies() 的目的是将这些类别转换为01。这使得计算机程序更容易理解和处理数据。

在虚拟变量的上下文中

  1. 1表示特定类别的存在。
  2. 0表示特定类别的缺席。

在 Pandas 中,我们使用 get_dummies() 函数将分类变量转换为二元值。


在 Pandas Series 上使用 get_dummies()

在 Pandas 中,要在 Series 上使用 get_dummies(),我们将 Series 传递到函数中。例如,

import pandas as pd

# create a Panda Series
data = pd.Series(['A', 'B', 'A', 'C', 'B'])

# using get_dummies on the Series
dummies = pd.get_dummies(data)

print(dummies)

输出

   A  B  C
0  1  0  0
1  0  1  0
2  1  0  0
3  0  0  1
4  0  1  0

在上面的示例中,列 ABC 包含二元值(10),指示 data Series 中每行的每个类别的存在或缺席。


在 DataFrame 列上使用 get_dummies()

我们还可以使用 Pandas 中的 aggregate() 函数对一个或多个列应用多个聚合函数。例如,

import pandas as pd

# sample data
data = {'Color': ['Red', 'Green', 'Blue', 'Green', 'Red']}

# creating a DataFrame
df = pd.DataFrame(data)

# using get_dummies to convert the categorical column
dummies = pd.get_dummies(df['Color'])

# concatenating the dummies DataFrame with the original DataFrame
df = pd.concat([df, dummies], axis=1)

print(df)

输出

    Color    Blue  Green  Red
0   Red       0      0     1
1   Green     0      1     0
2   Blue      1      0     0
3   Green     0      1     0
4   Red       0      0     1

在此示例中,我们将 get_dummies() 函数应用于 df DataFrame 的 Color 列。

此函数将 Color 列中的分类值转换为一组二元指示列。

在这种情况下,由于有三种独特的颜色 RedGreenBlue,因此这三列新增了。

这些列中的值1表示该行存在相应的颜色,0表示不存在。

注意axis=1 指的是沿列或水平轴的操作。这意味着操作将逐列应用于 DataFrame。


在 get_dummies() 中使用 drop_first

在 Pandas 中,我们可以使用 get_dummies() 函数为 DataFrame 中的分类列创建虚拟变量,然后使用 drop_first 参数删除第一个类别。

让我们看一个例子。

import pandas as pd

# sample data
data = {'Color': ['Red', 'Green', 'Blue', 'Green', 'Red']}

# creating a DataFrame
df = pd.DataFrame(data)

# getting dummies without dropping any columns
dummies_all = pd.get_dummies(df['Color'])

# concatenating the dummies DataFrame with the original DataFrame
df_all = pd.concat([df, dummies_all], axis=1)

print("DataFrame with all dummy columns:")
print(df_all)
print("\n")

# getting dummies and dropping the first category column ('Blue' in this case)
dummies = pd.get_dummies(df['Color'], drop_first=True)

# concatenating the dummies DataFrame with the original DataFrame
df = pd.concat([df, dummies], axis=1)

print("DataFrame after dropping 'Blue':")
print(df)

输出

DataFrame with all dummy columns:
   Color  Blue  Green  Red
0  Red     0      0     1
1  Green   0      1     0
2  Blue    1      0     0
3  Green   0      1     0
4  Red     0      0     1


DataFrame after dropping 'Blue':
   Color  Green  Red
0  Red      0     1
1  Green    1     0
2  Blue     0     0
3  Green    1     0
4  Red      0     1

在这里,将 drop_first=True 参数传递给 get_dummies() 以指示应删除第一个类别。

因此,生成的 DataFrame 包含两列 GreenRed。名为 Blue 的类别未在此列中表示,因为它已被删除。


在 get_dummies() 中使用 prefix

我们可以使用 get_dummies() 函数内的 prefix 参数为从 DataFrame 列创建的虚拟变量指定前缀。

让我们看一个例子。

import pandas as pd

# sample data
data = {'Color': ['Red', 'Green', 'Blue', 'Green', 'Red']}

# creating a DataFrame
df = pd.DataFrame(data)

# getting dummies with a specified prefix
dummies = pd.get_dummies(df['Color'], prefix='Color')

# concatenating the dummies DataFrame with the original DataFrame
df = pd.concat([df, dummies], axis=1)

print(df)

输出

   Color Color_Blue Color_Green  Color_Red
0  Red        0          0            1
1  Green      0          1            0
2  Blue       1          0            0
3  Green      0          1            0
4  Red        0          0            1

在这里,我们将 prefix='Color' 参数传递给了 get_dummies(),因此新的虚拟变量列的前缀是 Color_

因此,生成的 DataFrame 包含 Color_BlueColor_GreenColor_Red 列,表示相应颜色类别的存在或缺席。

注意:如需了解更多信息,请访问 Pandas get_dummies()

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战