我正在运行以下脚本:
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/