python numpy.savetxt 一个混合格式的矩阵

标签 python numpy

我正在尝试将矩阵另存为文本,该矩阵每行有 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/

相关文章:

python - Discord.py 禁止命令

Python:使用父类的构造函数初始化对象的成员?

python - 我可以使用 Numpy 获得矩阵行列式吗?

python - 如何查找特定值的列号以及该位置的 CSV 文件

python - 需要将特定的列集转换为行,并将其余列转换为重复值

python - Django autocomplete_light 和 city_light - 无效选择

python - 使用python清理大数据

python - Dropbox webhook,检测已删除的文件

Python 条形图重叠

python - 64 位系统,8GB 内存,略多于 800MB 的 CSV,用 python 读取会出现内存错误