首页 > 解决方案 > 如何解决 ValueError: could not convert string to float in python

问题描述

我有数据集的文本文件,看起来像这样。

2.8858451e-001 -2.0294171e-002 -1.3290514e-001 -9.9527860e-001 -9.8311061e-001

当我阅读此文件并在此数据上拟合分类器时,我收到此错误。

ValueError:无法将字符串转换为浮点数:' 2.3177399e-001 4.9371571e-003

我正在使用以下代码:

tra_x, tra_y, tes_x, tes_y = np.array([]), np.array([]), np.array([]),np.array([]) 

file = open('train\X_train.txt', encoding='utf-8') 
tra_x = file.readlines()
tra_x = [float(x).split(" ") for x in tra_x] 

file = open('train\y_train.txt', encoding='utf-8') 
tra_y = file.readlines() 

file = open('test\X_test.txt', encoding='utf-8') 
tes_x = file.readlines() 

file = open('test\y_test.txt', encoding='utf-8') 
tes_y = file.readlines() 

标签: pythonpython-3.x

解决方案


以下代码适用于单行:

[float(x) for x in "2.8858451e-001 -2.0294171e-002 -1.3290514e-001 -9.9527860e-001 -9.8311061e-001".split(" ")]

数字是一长串。您需要分隔空格并将每个字符串分别转换为浮点数

对于多行:

return_list = []
for l in tra_x:
    for entry in l.split(" "):
        return_list.append(float(entry))

推荐阅读