python numpy.savetext混合格式的矩阵 [英] python numpy.savetext a matrix with mixed format

查看:424
本文介绍了python numpy.savetext混合格式的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个矩阵保存为文本,该矩阵在每行288浮点数和末尾有1个字符串,我已经使用了savetxt:

I am trying to save as text a matrix which has in each row 288 float and 1 string at the end, i've used the savetxt like this:

np.savetxt('name', matrix, delimiter='  ', header='string', comments='', fmt= '%3f'*288 + '%s')

但是当我尝试运行代码时,它会引发如下异常:

but when I try to run the code it raises exceptions like this:

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')

我真的不明白我哪里错了.

I really can't understand where I am wrong.

推荐答案

您的错误消息表明您正在提供字符串数据(dtype ('<U32'))-U32代表

Your error message says that you are providing string data (dtype ('<U32')) -U32 stands for Unicode string- but your format specifier is floating numbers followed by a string ('%3f(repeated 288 times without spaces)%s').

由于矩阵已经是字符串,因此无论如何都无法对其进行格式化.如果您对浮点数字不满意,则可能应在输入此矩阵之前对其进行格式化.

Since your matrix is already string there is no point in trying to format it anyway. If you are not satisfied with the floating point digits you should probably format it before entering to this matrix.

因此,在您的情况下,只需编写当前矩阵即可:

So, in your case to just write your present matrix just use:

np.savetxt('name', matrix, delimiter='  ', header='string', comments='', fmt='%s')

将每个元素视为一个字符串(它们实际上是字符串)并将其写入文本文件.

which will treat each element as a string (which they actually are) and write it to the text file.

也许这

Also maybe this answer provide some clues if you are not satisfied.

这篇关于python numpy.savetext混合格式的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆