python-3.x - 从数据子集的列中创建虚拟对象,其中不包含该列中的所有类别值

标签 python-3.x pandas one-hot-encoding

我正在处理大型数据集的一个子集。

数据框中有一个名为“type”的列。 “类型”应具有类似 [1,2,3,4] 的值。

在某个子集中,我发现“类型”列仅包含某些值,例如 [1,4],例如

 In [1]: df
 Out[2]:
          type
    0      1
    1      4

当我从该子集的“类型”列创建虚拟对象时,结果是这样的:
In [3]:import pandas as pd
In [4]:pd.get_dummies(df["type"], prefix = "type")
Out[5]:        type_1 type_4
        0        1       0
        1        0       1

它没有名为“type_2”、“type_3”的列。我想要的是:
 Out[6]:        type_1 type_2 type_3 type_4
            0      1      0       0      0
            1      0      0       0      1

有解决方案吗?

最佳答案

您需要做的是制作专栏'type' pd.Categorical 并指定 categories

pd.get_dummies(pd.Categorical(df.type, [1, 2, 3, 4]), prefix='type')

   type_1  type_2  type_3  type_4
0       1       0       0       0
1       0       0       0       1

关于python-3.x - 从数据子集的列中创建虚拟对象,其中不包含该列中的所有类别值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648954/

相关文章:

python-3.x - Pyinstaller 不会在 Python 虚拟环境中查找文件

python - 在数据框中插入记录的 concat 的替代方法

pandas - 在 Pandas 数据框中创建一个包含 bool 列组合计数的方阵

encoding - 使用sklearn进行一次热编码后,如何给出列名?

python - 为 onehotencoded 变量创建管道不起作用

python - 如何使用winsound模块同时播放多个频率

python - 从多个进程将数据添加到队列

python - 广泛覆盖运算符(使用 "=="进行类型检查)

python-3.x - Pandas Dataframe 显示具有所需条件的行

python - OneHotEncoder 对属于同一类别的多个列进行处理