【发布时间】:2021-09-11 07:23:40
【问题描述】:
想象一下,我在 3 列中有 4 个类别,但这些类别在列中重复出现。比如……
df1 = pd.DataFrame(data=[['a', 'b', 'c'], ['b', 'a', 'd'], ['a', 'c', 'd'], ['b', 'd', 'a']])
0 1 2
0 a b c
1 b a d
2 a c d
3 b d a
当我转换时,我得到 8 列,而我应该只得到 4 列(每个类别(a、b、c 和 d)一个。
ohe = ColumnTransformer([('ohe', OneHotEncoder(categories='auto', sparse=False), [0, 1, 2])], remainder='passthrough')
df2 = ohe.fit_transform(df1)
作为 df2 的八个列类别,但我只想获得四个...在我的列中分布的每个“a”、“b”、“c”和“d”类别。
有没有办法获得这个输出?
Out[17]:
a b c d
0 1 1 1 0
1 1 1 0 1
2 1 0 1 1
3 1 1 0 1
【问题讨论】:
标签: python pandas one-hot-encoding dummy-variable