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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22118648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:16:47  来源:igfitidea点击:

How to write a numpy matrix in a text file - python

pythonnumpymatrixtext-files

提问by Nafees

Suppose I am getting a numpy matrix from some calculation. Here is my numpy matrix 'result1'::

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

Now I want to write this matrix in a text file named 'result.txt'. For this, I wrote the following code::

现在我想将此矩阵写入名为“result.txt”的文本文件中。为此,我编写了以下代码:

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

But it is giving me all the elements of the matrix in one row.

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

    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

I want to write the matrix in the text file in the proper matrix format. How can I do this? I used keyword newline='\n' or newline='',but the result is same.

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

Thanks in advance...

提前致谢...

=======

========

This edited part is for @Warren

此编辑部分适用于@Warren

try this one:

试试这个:

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

in my text.txt file, I am getting:

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

1.00 2.00 3.004.00 5.00 6.007.00 8.00 9.00

1.00 2.00 3.004.00 5.00 6.007.00 8.00 9.00

回答by dawg

To recreate the shape, you need to save the shape when you save the file.

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

Try:

尝试:

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

You can save the shape in some form in the file in oder to recreate the same shape. Make sure you do not forget the data at the beginning of the file however, since unlike np.loadtxt, lines starting with #are still considered data.

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

回答by Francesco Nazzaro

If you want to use only numpy:

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

and then

进而

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

Pandas has to_csvmethod:

熊猫有to_csv方法:

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)

it has the same output:

它具有相同的输出:

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

回答by DAYHU

like Francesco Nazzaro's answer, but a little different to make sure the file can be opened successfully, try:

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