【问题标题】:could not convert string to float from file.txt无法将字符串从 file.txt 转换为浮点数
【发布时间】:2020-03-07 18:16:14
【问题描述】:

我正在尝试从文件中读取字符串数组并将其转换为浮点数组。总而言之,我正在尝试做类似的事情:

input_X = np.random.rand(2, 5)

with open ("prueba1.txt", "w") as fichero:
    fichero.write(str(input_X))

with open("prueba1.txt", "r") as fichero:
    x = fichero.read()


y = np.array(x)
y = y.astype(np.float)

然后:

ValueError: could not convert string to float: '[[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01\n  1.46755891e-01]\n [9.23385948e-02 1.86260211e-01 3.45560727e-01 3.96767474e-01\n  5.38816734e-01]]'

有人可以帮我吗?

【问题讨论】:

  • numpy 数组的str 旨在向您显示数组值和布局。从它重新创建数组是很尴尬的,如果不是不可能的话。它并不是一种文件保存格式。请查看 np.save/load 对函数。
  • astype(np.float) 可以转换像array(['1','2','3']) 这样的数组。 y 的各个元素必须是看起来像有效数字的字符串。 float('1')。但这不是您加载的内容。看看x 和np.array(x)。

标签: python string numpy


【解决方案1】:

为什么不简单

input_X = np.random.rand(2, 5)
np.savetxt('prueba1.txt', input_X)
y = np.loadtxt('prueba1.txt')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多