如何在文本文件中编写numpy矩阵 - python

Naf*_*ees 9 python numpy matrix text-files

假设我从一些计算得到一个numpy矩阵.这是我的numpy矩阵'result1'::

    result1=
    [[   1.         0.         0.         0.00375   -0.01072   -0.      -1000.     ]
     [   2.         3.         4.         0.        -0.004    750.         0.     ]
     [   3.         3.         0.         0.         0.      -750.      1000.     ]]
Run Code Online (Sandbox Code Playgroud)

现在我想在名为'result.txt'的文本文件中写这个矩阵.为此,我写了以下代码::

np.savetxt('result.txt', result1, fmt='%.2e')
Run Code Online (Sandbox Code Playgroud)

但是它给了我一行矩阵的所有元素.

    1.00e+00 0.00e+00 0.00e+00 3.75e-03 -1.07e-02 -1.14e-13 -1.00e+032.00e+00 3.00e+00 4.00e+00 0.00e+00 -4.00e-03 7.50e+02 0.00e+003.00e+00 3.00e+00 0.00e+00 0.00e+00 0.00e+00 -7.50e+02 1.00e+03
Run Code Online (Sandbox Code Playgroud)

我想以适当的矩阵格式在文本文件中编写矩阵.我怎样才能做到这一点?我使用了关键字newline ='\n'或newline ='',但结果是一样的.

提前致谢...

=======

这个编辑的部分是为@Warren

试试这个:

>>> import numpy as np
>>> mat=np.matrix([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
>>> mat
matrix([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
>>> np.savetxt('text.txt',mat,fmt='%.2f')
Run Code Online (Sandbox Code Playgroud)

在我的text.txt文件中,我得到:

1.00 2.00 3.004.00 5.00 6.007.00 8.00 9.00

DAY*_*YHU 7

像 Francesco Nazzaro 的回答,但有点不同以确保文件可以成功打开,请尝试:

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
mat = np.matrix(a)
with open('outfile.txt','wb') as f:
    for line in mat:
        np.savetxt(f, line, fmt='%.2f')
Run Code Online (Sandbox Code Playgroud)


daw*_*awg 2

要重新创建形状,您需要在保存文件时保存形状。

尝试:

import numpy as np
import re

result=np.array([[1.,0.,0.,0.00375,-0.01072,-0.,-1000.,],
                 [2.,3.,4.,0.,-0.004,750.,0.],
                 [3.,3.,0.,0.,0.,-750.,1000.]])

with open('/tmp/test', 'w') as fout:
    fout.write(u'#'+'\t'.join(str(e) for e in result.shape)+'\n')
    result.tofile(fout)

with open('/tmp/test', 'rb') as f:
    line=f.readline().decode('ascii')
    if line.startswith('#'):
        shape=tuple(map(int, re.findall(r'(\d+)', line)))
    else:
        raise IOError('Failed to find shape in file')    

    result2=np.fromfile(f)
    result3=result2.reshape(shape)

print(np.array_equal(result, result2))
# False
print(np.array_equal(result, result3))
# True
Run Code Online (Sandbox Code Playgroud)

您可以将形状以某种形式保存在文件中,以便重新创建相同的形状。但请确保您不要忘记文件开头的数据,因为与np.loadtxt不同,以 开头的行#仍被视为数据。