我正在尝试将矩阵另存为文本,该矩阵每行有 288 个 float ,末尾有 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
代表Unicode string - 但您的格式说明符是 float ,后跟一个字符串( '%3f(repeated 288 times without spaces)%s'
)。
由于您的矩阵已经是字符串,因此无论如何都没有必要尝试对其进行格式化。如果您对 float 字不满意,您可能应该在输入此矩阵之前对其进行格式化。
因此,在您的情况下,只需编写您现在的矩阵即可:
np.savetxt('name', matrix, delimiter=' ', header='string', comments='', fmt='%s')
这会将每个元素视为一个字符串(它们实际上是)并将其写入文本文件。
也可能是这个 answer如果您不满意,请提供一些线索。
关于python numpy.savetxt 一个混合格式的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49670586/