pandas sklearn-LinearRegression:无法将字符串转换为浮点数:'--'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46092914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:24:53  来源:igfitidea点击:

sklearn-LinearRegression: could not convert string to float: '--'

pythonpandasscikit-learnvalueerror

提问by Tinniam V. Ganesh

I am trying to use a LinearRegression from sklearn and I am getting a 'Could not convert a string to float'. All columns of the dataframe are float and the output y is also float. I have looked at other posts and the suggestions are to convert to float which I have done.

我正在尝试使用来自 sklearn 的 LinearRegression,但我收到“无法将字符串转换为浮点数”的消息。数据帧的所有列都是浮动的,输出 y 也是浮动的。我看过其他帖子,建议是转换为我已经完成的浮动。

<class 'pandas.core.frame.DataFrame'>
Int64Index: 789 entries, 158 to 684
Data columns (total 8 columns):
f1     789 non-null float64
f2     789 non-null float64
f3     789 non-null float64
f4     789 non-null float64
f5     789 non-null float64
f6     789 non-null float64
OFF    789 non-null uint8
ON     789 non-null uint8
dtypes: float64(6), uint8(2)
memory usage: 44.7 KB

type(y_train)
pandas.core.series.Series
type(y_train[0])
float

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,Y,random_state=0)
X_train.head()
from sklearn.linear_model import LinearRegression
linreg = LinearRegression().fit(X_train, y_train)

The error I get is a

我得到的错误是

ValueError                                Traceback (most recent call last)
<ipython-input-282-c019320f8214> in <module>()
      6 X_train.head()
      7 from sklearn.linear_model import LinearRegression
----> 8 linreg = LinearRegression().fit(X_train, y_train)
510         n_jobs_ = self.n_jobs
    511         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
--> 512                          y_numeric=True, multi_output=True)
    513 
    514         if sample_weight is not None and np.atleast_1d(sample_weight).ndim > 1:

 527         _assert_all_finite(y)
    528     if y_numeric and y.dtype.kind == 'O':
--> 529         y = y.astype(np.float64)
    530 
    531     check_consistent_length(X, y)

ValueError: could not convert string to float: '--'

Please help.

请帮忙。

回答by cs95

A quick solution would involve using pd.to_numericto convert whatever strings your data might contain to numeric values. If they're incompatible with conversion, they'll be reduced to NaNs.

一个快速的解决方案是使用pd.to_numeric将数据可能包含的任何字符串转换为数值。如果它们与转换不兼容,它们将被简化为NaNs。

from sklearn.linear_model import LinearRegression

X = X.apply(pd.to_numeric, errors='coerce')
Y = Y.apply(pd.to_numeric, errors='coerce')

Furthermore, you can choose to fill those values with some default:

此外,您可以选择使用一些默认值填充这些值:

X.fillna(0, inplace=True)
Y.fillna(0, inplace=True)

Replace the fill value with whatever's relevant to your problem. I don't recommend dropping these rows, because you might end up dropping different rows from Xand Ycausing a data-label mismatch.

用与您的问题相关的任何内容替换填充值。我不建议删除这些行,因为您最终可能会删除不同的行XY导致数据标签不匹配。

Finally, split and call your classifier:

最后,拆分并调用您的分类器:

X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state=0)
clf = LinearRegression().fit(X_train, y_train)

回答by Sagar Narula

I think its better to convert all the string columns to binary(0,1) using the label encoding or one hot encoding after than our linear regression will behave much better.!!

我认为最好使用标签编码或一种热编码将所有字符串列转换为二进制(0,1),而不是我们的线性回归表现得更好。!!