首页 > 解决方案 > sklearn OneHotEncoding 与 ColumnTransformer

问题描述

我在我的数据集的第 8 列上有分类数据。我希望对这些数据进行编码,并且我正在使用 ColumnTransformer。我第一次尝试使用这种方法时,我使用了代码:

from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.compose import ColumnTransformer

#encoding categorical data for dept column(independent variables)
ct = ColumnTransformer(transformers=[('one_hot_encoder',OneHotEncoder(categories='auto'), [0])],
                       remainder='passthrough')
X = np.array(ct.fit_transform(X), dtype=np.float)

请注意,我正在使用 LabelEncoder 对我的因变量进行编码,并且效果很好。现在的问题是,当我第一次执行此代码时没有错误,但是当我将列索引更改为在我的情况下说 [8] 时,我得到与索引 [0] 有关的错误。 ValueError: could not convert string to float: 'Emp ID' 这我认为引发了两个问题,首先我的列标题没有被这样读取,其次,索引没有被更改为 8。

我已添加:drop='first'希望删除列 [0] 但无济于事

标签: pythonscikit-learn

解决方案


为什么不使用 Keras to_categorical

from keras.utils.np_utils import to_categorical

X = to_categorical(X)

推荐阅读