ValueError:无法将字符串转换为浮点数:'Bad'
Posted
技术标签:
【中文标题】ValueError:无法将字符串转换为浮点数:\'Bad\'【英文标题】:ValueError: could not convert string to float: 'Bad'ValueError:无法将字符串转换为浮点数:'Bad' 【发布时间】:2021-04-12 11:33:28 【问题描述】:import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
df = pd.read_csv('CarSeats_Dataset.csv')
df=df.dropna()
dummies=pd.get_dummies(df[['ShelveLoc', 'Urban', 'US']])
X = df.drop('Sales',axis=1)
y = np.log(df['Sales'])
X_train, X_test , y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
regressor = DecisionTreeRegressor(random_state = 42)
regressor.fit(X_train, y_train)
我试图预测销售额,但在尝试拟合回归量时出现错误:
【问题讨论】:
如果是文本,您需要使用 tf idf、w2v 等将字符串值转换为向量嵌入。对于类别:一种热编码 【参考方案1】:import pandas as pd
Data = 'Product': ['ABC','XYZ'],
'Price': ['250','270']
df = pd.DataFrame(Data)
df['Price'] = df['Price'].astype(float)
print (df)
print (df.dtypes)
【讨论】:
考虑解释你的代码究竟做了什么,这不仅有助于 OP 和未来的读者,而且不仅仅是没有上下文的代码以上是关于ValueError:无法将字符串转换为浮点数:'Bad'的主要内容,如果未能解决你的问题,请参考以下文章
ValueError:无法将字符串转换为浮点数:'2100 - 2850'
ValueError:无法将字符串转换为浮点数:'62,6'
ValueError:无法将字符串转换为浮点数:''20,99''