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

2024-09-28 16:22:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我从计算中得到一个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


Tags: 代码textnumpytxt元素npnewline矩阵
3条回答

如果只想使用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

熊猫有^{}方法:

import numpy as np
import pandas as pd

mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = 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

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

尝试:

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

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

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

相关问题 更多 >