python - 如何解决 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()
解决方案
以下代码适用于单行:
[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))
推荐阅读
- c# - 使用 MailKit 的单个 SMTP 事务向多个收件人发送电子邮件
- python - 按组过滤,其中熊猫系列值增加
- python-3.x - python websocket中的回调函数出错:第346行,_callback回调(self,*args)
- java - Aeron 基本发布/订阅对在同一主机上连接,跨主机失败
- json - 在json正文中发送多个文件
- performance - 在执行相同的转换集时,ADF 映射数据流的性能与 Databricks 相比非常低
- haskell - 如何使用自定义的 `parseJSON` 解码 JSON - 一个函数而不是与 `fromJSON` 的实例相关的函数?
- c++ - GCC 中格式错误的 C/C++ 多维数组初始化
- mysql - 创建类别列mysql
- couchbase - 向 couchbase REST API 端点添加身份验证?