ValueError:无法将字符串转换为float:'France'

时间:2019-06-10 14:43:10

标签: python machine-learning scikit-learn

在Python中使用oneHotEncoder时出错。

在Udemy课程之后,我正在使用Python学习机器学习。当我尝试使用oneHotEncorder在源数据中对国家/地区名称进行编码时,出现以下错误。

array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: could not convert string to float: 'France'

代码:

from sklearn.preprocessing import OneHotEncoder
oneHotEncObj=OneHotEncoder(categorical_features=[0])
X=oneHotEncObj.fit_transform(X).toarray()

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

您正在寻找:https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html

尝试用preprocessing.LabelEncoder()替换onehotencoder

答案 1 :(得分:0)

LabelEncoder的fit_transform方法,适合标签编码器并返回编码的标签

因此,您需要将labelencoder_X.fit_transform(X [:,0])的返回值分配给X [:,0]

完整的代码将是

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:,0]= labelencoder_X.fit_transform(X[:,0])
oneHotEncoder = OneHotEncoder(categorical_features =[0])
X=oneHotEncoder.fit_transform(X).toarray()