"ValueError: could not convert string to float" while using OneHotEncoder for machine learning

"ValueError: could not convert string to float" while using OneHotEncoder for machine learning

我正在使用 LabelEncoder 和 OneHotEncoder 来处理我的数据集中的 'categorical data'。在我的数据集中,有一列可以有两个值 'Petrol' 或 'Diesel',我想对该列进行编码。我是 运行 这段代码,它给出了一个错误。

import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder,OneHotEncoder

dataset = pd.read_csv('ToyotaCorolla.csv')
X = dataset.iloc[:, 1:10].values
y = dataset.iloc[:, 0].values

labelencoder_X = LabelEncoder()
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()

列[3] 是具有分类值的列。但它显示错误 "ValueError: could not convert string to float: 'Diesel'"。 我不知道我哪里错了。请帮忙。谢谢!

categorical_features 已弃用,而是直接转换您的分类特征

onehotencoder = OneHotEncoder(categories='auto')
feature = onehotencoder.fit_transform(X[:, 3].reshape(-1, 1))

当你的 x 有一个类别为字符串格式的列时,就会出现这个错误 当我有这个错误 我对 X 中的所有分类列使用了标签编码器,就像您对第 3 列所做的那样 然后将一个热编码器应用于第 3 列

"so what you have to do is LabelEncode all the categorical columns in X and then apply one hot encoder to your desired column"