【问题标题】:Linear Regression could not convert string to float线性回归无法将字符串转换为浮点数
【发布时间】:2018-09-14 03:19:17
【问题描述】:

我正在尝试通过线性回归找到 UCAS 分数和最终大学分数(Final)之间的关系,我正在使用 This 教程

我收到以下错误

plt.scatter(X_test, Y_test,  color='black') 

无法将字符串转换为浮点数:

我检查了类型,“Total UCAS Points”列属于 str 类,“Final”属于 numpy.float64' 类型

我尝试通过执行以下操作将 str 转换为浮点数:

pd.to_numeric("Total UCAS Points")

但不断收到错误消息:

无法解析位置 0 处的字符串“Total UCAS Points”

我也尝试忽略该错误,但这似乎并没有将类型更改为 float 并且仍然是 str

这是我的 csv 文件的示例:

UCAS 总分: 280 280 240 240 360 360 360 360 630

决赛: 58 46 62 64 48 56 54 30

df = df.replace(np.nan, -1)

X = df['Total UCAS Points']
Y = df['Final']

pd.to_numeric("Total UCAS Points")

print(type(Y[2]))


X=X.reshape(len(X),1)
Y=Y.reshape(len(Y),1)

# Split the data into training/testing sets
X_train = X[:-2500]
X_test = X[-2500:]

# Split the targets into training/testing sets
Y_train = Y[:-2500]
Y_test = Y[-2500:]

# Plot outputs
plt.scatter(X_test, Y_test,  color='black')

【问题讨论】:

    标签: python machine-learning linear-regression


    【解决方案1】:

    您需要将数据列表传递给to_numeric,而不是数据框中的列名。试试这个:

    X = pd.to_numeric(X)  # in place of pd.to_numeric("Total UCAS Points")
    

    【讨论】:

    • 谢谢,我现在意识到这个问题有多愚蠢。您能指导我如何从“UCAS 总积分”中删除空字符串吗?我认​​为 df.replace 会处理这个问题,但我想这仅适用于 NaN 值。我现在收到以下错误:无法在位置 22 解析字符串“”。
    • 我发现:df = df.replace(r'^\s+$', np.nan, regex=True) 适用于空白空间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多