python - scikit-learn 中的 "ValueError: could not convert string to float"错误

标签 python numpy scikit-learn

我正在运行以下脚本:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
dataset = pd.read_csv('data/50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
onehotencoder = OneHotEncoder(categorical_features=3, 
handle_unknown='ignore')
onehotencoder.fit(X)

数据头看起来像:
data

我有这个:

ValueError: could not convert string to float: 'New York'



我阅读了 similar 的答案问题然后打开 scikit-learn documentations ,但是如何查看 scikit-learn 作者没有字符串中的空格问题

我知道我可以使用 LabelEncocder来自 sklearn.preprocessing然后使用 OHE 并且效果很好,但在这种情况下
In case you used a LabelEncoder before this OneHotEncoder to convert the categories to integers, then you can now use the OneHotEncoder directly.
warnings.warn(msg, FutureWarning)

发生按摩。

您可以使用 full csv file或者
[[165349.2, 136897.8, 471784.1, 'New York', 192261.83],
[162597.7, 151377.59, 443898.53, 'California', 191792.06],
[153441.51, 101145.55, 407934.54, 'Florida', 191050.39],
[144372.41, 118671.85, 383199.62, 'New York', 182901.99],
[142107.34, 91391.77, 366168.42, 'Florida', 166187.94]]

5 第一行来测试此代码。

最佳答案

categorical_features=3那会伤害你。您不能使用 categorical_features与字符串数据。删除此选项,您将有好运。此外,您可能需要 fit_transform ,不是 fit像这样。

onehotencoder = OneHotEncoder(handle_unknown='ignore')
transformed = onehotencoder.fit_transform(X[:, [3]]).toarray()
X1 = np.concatenate([X[:, :2], transformed, X[:, 4:]], axis=1)
#array([[165349.2, 136897.8, 0.0, '0.0, 1.0, 192261.83],
#       [162597.7, 151377.59, 1.0, 0.0, 0.0, 191792.06],
#       [153441.51, 101145.55, 0.0, 1.0, 0.0, 191050.39],
#       [144372.41, 118671.85, 0.0, 0.0, 1.0, 182901.99],
#       [142107.34, 91391.77, 0.0, 1.0, 0.0, 166187.94']])

关于python - scikit-learn 中的 "ValueError: could not convert string to float"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473274/

相关文章:

python - 解析\xd0\xb2\xd0\xbe 等时出现问题

python - 在python和matlab中将浮点二进制文件读入二维数组

python - 比较两个文件中的 x、y、z 坐标

python - 值错误 : operands could not be broadcast together with shapes - inverse_transform- Python

python - 线(旅行路径)聚类机器学习算法

python - Scikit SGDClassifier 使用字母而不是单词作为特征

python - Django 模型选择选项,填充了来自其他模型实例的字段

python - 如何加载重载方法

python - 如何将空工作表添加到已使用 pandas 创建的 `excel` 文件中

python - numpy 中的数组按行排序