Python 无法将字符串从file.txt转换为float
我试图从一个文件中读取一个字符串数组,并将其转换为浮点数组。总而言之,我正在尝试做一些类似的事情:Python 无法将字符串从file.txt转换为float,python,string,numpy,Python,String,Numpy,我试图从一个文件中读取一个字符串数组,并将其转换为浮点数组。总而言之,我正在尝试做一些类似的事情: 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.ast
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]]'
有人能帮我吗?为什么不干脆
input_X = np.random.rand(2, 5)
np.savetxt('prueba1.txt', input_X)
y = np.loadtxt('prueba1.txt')
numpy数组的
str
用于显示数组值和布局。从中重新创建阵列即使不是不可能,也是很尴尬的。它不是用来保存文件的格式。查看np.save/load
函数对。astype(np.float)
可以转换类似array(['1'、'2'、'3'])的数组。
。y
的各个元素必须是看起来像有效数字的字符串<代码>浮动('1')。但那不是你要装的东西。查看x
和np.array(x)
。