【问题标题】:Save numpy ndarray into a txt file将 numpy ndarray 保存到 txt 文件中
【发布时间】:2017-07-13 07:07:02
【问题描述】:

我有一个<class 'numpy.ndarray'> 对象,我希望将它保存在一个txt 文件中。该对象的尺寸(形状)(130, 118, 118) 和大小1810120

当我尝试将np.savetxt(f, object, delimiter=' ', fmt='1.10f')f = open('test.txt', 'wb') 一起使用时,我收到错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\G****\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1139, in savetxt
    raise error
ValueError: fmt has wrong number of % formats:  1.10f

我尝试了 1.f 的各种组合,但都没有奏效。有人建议吗?

更新: 在遵循 cmets 的建议后,添加fmt='%1.10f' 我收到了这个:

Traceback (most recent call last):
  File "C:\Users\G****\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1158, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: only length-1 arrays can be converted to Python scalars

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\G****\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1162, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('int8') and format specifier ('%1.10f...... the '%1.10f goes on for quite a while)

【问题讨论】:

  • 试试:fmt='%1.10f'

标签: python numpy


【解决方案1】:

尝试添加%,例如使用fmt='%1.10f'。见here

更新:

import numpy as np

obj = np.random.randint(10, size=(3, 4, 5), dtype=np.int8)  # example array

with open('test.txt', 'wb') as f:
    np.savetxt(f, np.column_stack(obj), fmt='%1.10f')

注意最后一行的np.column_stack(obj) 并阅读this 以了解此处使用它的原因。但是,如果您的 numpy 数组包含整数,您可能希望使用 fmt='%s'。此外,np.row_stack(obj) 可能是一个有用的替代方案,具体取决于文件的外观。

【讨论】:

  • 谢谢!你能再检查一下我编辑的答案吗?
  • 你的numpy数组的元素是8位整数吗?
  • 是的,没错。这是否意味着我无法保存它们?
  • 你可能想看看this
  • 不幸的是并没有真正帮助。我试过了:with open('test.txt', 'wb') as f: np.savetxt(f, object, fmt='%.10f') 但我得到了同样的错误
猜你喜欢
  • 2021-03-23
  • 2020-06-11
  • 2018-12-15
  • 2018-07-15
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多