在 python 中将大型矩阵保存到 .txt 文件中

Saving a large matrix in to a .txt file in python

我想知道将大型矩阵(在我的情况下是 640x640 元素)保存到更容易概览的 .txt 文件中的最简单方法是什么。

我一直在尝试将每个元素转换为字符串然后保存,但我从未设法获得一个正确的、类似矩阵的有组织的 .txt 文件。

所以我想以完全相同的顺序保存所有元素,也许我会添加额外的行和列来枚举行(从 -320 到 +320)和列。

我想这对你们中的一些人来说很常见,他们会定期这样做,所以我想知道是否有人愿意分享他的知识并可能展示一个随机矩阵的例子...

卢卡

示例:

a = [[1,2],[3,4],[5,6]] # nested list
b = np.array(a)         # 2-d array
array([[1, 2],
   [3, 4],
   [5, 6]])
c = np.array2string(b)  # '[[1 2]\n [3 4]\n [5 6]]'. You can save this. Or
np.savetxt('foo', b)    # It saves to foo file while preserving the 2d array shape

尝试使用numpy.savetxt()numpy.loadtxt()将矩阵写入文件以及将文件读取到矩阵。

#write matrix to file 
import numpy 
my_matrix = numpy.matrix('1 2; 3 4')
numpy.savetxt('matrix.txt', my_matrix, delimiter = ',')  

#read file into a matrix
import numpy  
my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)

matrix.txt 看起来像:

1.000000000000000000e+00,2.000000000000000000e+00
3.000000000000000000e+00,4.000000000000000000e+00

如果你必须把它放在一个文本文件中,你可以做一些像这样简单的事情,这可能比其他答案更容易理解:

def write_matrix_to_textfile(a_matrix, file_to_write):

    def compile_row_string(a_row):
        return str(a_row).strip(']').strip('[').replace(' ','')

    with open(file_to_write, 'w') as f:
        for row in a_matrix:
            f.write(compile_row_string(row)+'\n')

    return True

这应该可以帮助您。我实际上没有 运行 这个,因为我没有 运行 它的矩阵。让我知道它是否适合你。