如果你阅读 OneHotEncoder
的文档,你会看到 fit
的输入是 "Input array of type int"。因此,对于你的独热编码数据,你需要执行两个步骤。
from sklearn import preprocessing
cat_features = ['color', 'director_name', 'actor_2_name']
enc = preprocessing.LabelEncoder()
enc.fit(cat_features)
new_cat_features = enc.transform(cat_features)
print new_cat_features
new_cat_features = new_cat_features.reshape(-1, 1)
ohe = preprocessing.OneHotEncoder(sparse=False)
print ohe.fit_transform(new_cat_features)
输出:
[[ 0. 1. 0.]
[ 0. 0. 1.]
[ 1. 0. 0.]]
编辑
从0.20
版本开始,这变得更加容易了,不仅因为OneHotEncoder
现在可以很好地处理字符串,而且还因为我们可以使用ColumnTransformer
轻松地转换多个列,下面是一个例子。
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import numpy as np
X = np.array([['apple', 'red', 1, 'round', 0],
['orange', 'orange', 2, 'round', 0.1],
['bannana', 'yellow', 2, 'long', 0],
['apple', 'green', 1, 'round', 0.2]])
ct = ColumnTransformer(
[('oh_enc', OneHotEncoder(sparse=False), [0, 1, 3]),],
remainder='passthrough'
)
print(ct2.fit_transform(X))
输出:
[['1.0' '0.0' '0.0' '0.0' '0.0' '1.0' '0.0' '0.0' '1.0' '1' '0']
['0.0' '0.0' '1.0' '0.0' '1.0' '0.0' '0.0' '0.0' '1.0' '2' '0.1']
['0.0' '1.0' '0.0' '0.0' '0.0' '0.0' '1.0' '1.0' '0.0' '2' '0']
['1.0' '0.0' '0.0' '1.0' '0.0' '0.0' '0.0' '0.0' '1.0' '1' '0.2']]
X = pd.DataFrame([['apple', 'red', 1, 'round', 0], ...
与ct = ColumnTransformer([('oh_enc', OneHotEncoder(sparse=False), [0, 1])], ...
一起使用会产生混合输出:[[1.0 0.0 0.0 0.0 0.0 1.0 0.0 1 'round' 0.0]...
- Sebastian Kropp