将numpy ndarray保存到txt文件中

时间:2017-02-23 00:34:29

标签: python numpy

我有一个<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但没有一个有效。建议任何人?

更新 按照下面的评论建议后,添加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)

1 个答案:

答案 0 :(得分: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)可能是一个有用的替代方案,具体取决于文件的外观。