[英]python numpy.savetext a matrix with mixed format
我试图将一个矩阵保存为文本,该矩阵在每行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
代表Unicode字符串 -但是您的格式说明符是浮点数后跟一个字符串( '%3f(repeated 288 times without spaces)%s'
)。
由于矩阵已经是字符串,因此无论如何都无法对其进行格式化。 如果您对浮点数字不满意,则可能应在输入此矩阵之前对其进行格式化。
因此,在您的情况下,只需编写当前矩阵即可:
np.savetxt('name', matrix, delimiter=' ', header='string', comments='', fmt='%s')
它将每个元素视为一个字符串(它们实际上是字符串)并将其写入文本文件。
如果您不满意,也可能此答案提供了一些线索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.