数据预处理错误OneHotEncoder错误

时间:2018-04-15 10:05:20

标签: python scikit-learn one-hot-encoding

数据预处理

导入库

import numpy as np #mathematical library 
import matplotlib.pyplot as plt #graphical library
import pandas as pd #for dataset

导入库

dataset = pd.read_csv('Data.csv')
X = dataset.iloc[ :, :-1].values
Y=dataset.iloc[:,3].values

照顾缺失的数据

from sklearn.preprocessing import Imputer
imputer= Imputer(missing_values='NaN',strategy='mean',axis=0)
imputer=imputer.fit(X[:,1:3])
X[:,1:3]=imputer.transform(X[:,1:3])

编码数据

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

X is array([['France', 44.0, 72000.0],
       ['Spain', 27.0, 48000.0],
       ['Germany', 30.0, 54000.0],
       ['Spain', 38.0, 61000.0],
       ['Germany', 40.0, 63777.77777777778],
       ['France', 35.0, 58000.0],
       ['Spain', 38.77777777777778, 52000.0],
       ['France', 48.0, 79000.0],
       ['Germany', 50.0, 83000.0],
       ['France', 37.0, 67000.0]], dtype=object)

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

请帮忙。

1 个答案:

答案 0 :(得分: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()