我试图将一个矩阵另存为文本,该矩阵每行有 288 个浮点数,末尾有 1 个字符串,我使用了这样的 savetxt:
np.savetxt('name', matrix, delimiter=' ', header='string', comments='', fmt= '%3f'*288 + '%s')
但是当我尝试运行代码时,它会引发如下异常:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\lib\npyio.py", line 1371, in savetxt
v = format % tuple(row) + newline
TypeError: must be real number, not numpy.str_
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\lib\npyio.py", line 1375, in savetxt
% (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U32') and format specifier ('%3f(repeated 288 times without spaces)%s')
我实在不明白我哪里错了。
您的错误消息表明您正在提供字符串数据(dtype ('<U32')
) -U32
代表统一码字符串 https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.dtypes.html- 但你的格式说明符是浮点数后跟一个字符串('%3f(repeated 288 times without spaces)%s'
).
由于您的矩阵已经是字符串,因此尝试格式化它是没有意义的。如果您对浮点数字不满意,您可能应该在输入该矩阵之前对其进行格式化。
因此,在您的情况下,只需编写当前矩阵即可使用:
np.savetxt('name', matrix, delimiter=' ', header='string', comments='', fmt='%s')
它将把每个元素视为一个字符串(它们实际上是)并将其写入文本文件。
也可能是这个answer https://stackoverflow.com/questions/16621351/how-to-use-python-numpy-savetxt-to-write-strings-and-float-number-to-an-ascii-fi如果您不满意,请提供一些线索。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)