我正在处理大型数据集的一个子集。
数据框中有一个名为“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/