我有一个像这样的数据集文本文件。
2.8858451e-001 -2.0294171e-002 -1.3290514e-001 -9.9527860e-001 -9.8311061e-001
当我读取此文件并将分类器适合此数据时,会出现此错误。
ValueError:无法将字符串转换为float:'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()
答案 0 :(得分:2)
以下代码适用于一行:
[float(x) for x in "2.8858451e-001 -2.0294171e-002 -1.3290514e-001 -9.9527860e-001 -9.8311061e-001".split(" ")]
数字长串。您需要分隔空格,并将每个字符串分别转换为float
多行:
return_list = []
for l in tra_x:
for entry in l.split(" "):
return_list.append(float(entry))