我有一个文本文件,其中包含较小的数据集(取自 csv 文件),如下所示 -
2020-05-24T10:44:37.613168#[ 0. 0. -0.06210425 0. ]
2020-05-24T10:44:37.302214#[1. 1. 0. 0.]
2020-05-24T10:44:36.192222#[0. 0. 0. 0.]
然后使用它读取
data = f.readlines()
for row in data:
img_id, label = row.strip("\n").split("#")
其中 label 是一个字符串列表,如下所示
[ 0. 0. -0.24604772 0. ]
[ 0. 0. -0.24604772 0. ]
[1. 1. 0. 0.]
我想将每个字符串元素转换为浮点数。然而,方括号[]
和小数.
阻止我转换。
到目前为止尝试过 -
去除[]
so - label = label[1:-1]
但稍后我需要它们作为数组。
然后这样做print([list(map(float, i.split())) for i in label])
导致错误ValueError: could not convert string to float: '.'
Using ast.literal_eval
.label = ast.literal_eval(row.strip("\n").split("#"))
。得到ValueError: malformed node or string: ['2020-05-24T10:57:52.882241 [0. 0. 0. 0.]']
Referred
需要将字符串读入浮点数组 https://stackoverflow.com/questions/21222702/need-to-read-string-into-a-float-array
无法使用 float() 将字符串列表转换为 python 中的浮点数列表 https://stackoverflow.com/questions/61953188/cannot-convert-list-of-strings-to-list-of-floats-in-python-using-float
如何使用 Python 将字符串列表转换为浮点数列表? https://stackoverflow.com/questions/51844300/how-do-you-convert-a-list-of-strings-to-a-list-of-floats-using-python
将字符串列表转换为浮点数的 numpy 数组 https://stackoverflow.com/questions/56642038/convert-list-of-strings-to-numpy-array-of-floats
何时使用 ast.literal_eval https://stackoverflow.com/questions/29552950/when-to-use-ast-literal-eval
So,
- 为了将它们转换为可迭代的浮点数组,我还应该尝试什么?或者我做错了什么?我应该去掉方括号吗?
- 如果我能让事情变得更容易,我怎样才能将数据存储在txt文件中?在这种情况下,CSV 比 txt 更好吗?
- 我需要将此逻辑扩展到 110,000 个条目。那么任何步骤都会导致问题吗?
谢谢。任何帮助将不胜感激。请帮忙。