【问题标题】:Saving a large matrix in to a .txt file in python在 python 中将大矩阵保存到 .txt 文件中
【发布时间】:2016-03-25 00:02:20
【问题描述】:

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

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

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

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

卢卡

【问题讨论】:

    标签: python python-2.7 python-3.x matrix save


    【解决方案1】:

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

    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
    

    这应该可以让你度过难关。我实际上并没有运行它,因为我没有一个矩阵来运行它。让我知道它是否适合你。

    【讨论】:

    • 感谢您的帮助,它确实有效,但不是我想要的 100%,因为我有 18 个列和很多行,所以它没有 640x640 所以正方形像形状......你能以某种方式定义每一行的宽度吗?也许尝试使用如下矩阵的函数:AMPL = 320; mat_from_to = np.zeros((AMPL*2,AMPL*2)) 这样你就知道我在说什么了......
    【解决方案2】:

    例子:

    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
    

    【讨论】:

      【解决方案3】:

      尝试使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多