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

时间:2014-03-01 18:40:31

标签: 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.     ]]

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

np.savetxt('result.txt', result1, fmt='%.2e')

但是它在一行中给了我矩阵的所有元素。

    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

我想以正确的矩阵格式在文本文件中编写矩阵。我怎样才能做到这一点?我使用了关键字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')

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

1.00 2.00 3.004.00 5.00 6.007.00 8.00 9.00

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

尝试:

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

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

答案 2 :(得分:1)

如果您只想使用numpy

import numpy as np

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

然后

cat outfile.txt
1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00

Pandas有to_csv方法:

import numpy as np
import pandas as pd

mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
dataframe = pd.DataFrame(data=mat.astype(float))
df.to_csv('outfile.csv', sep=' ', header=False, float_format='%.2f', index=False)

它具有相同的输出:

cat outfile.csv
1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00