【问题标题】:working with matrix and save everything in one txt file使用矩阵并将所有内容保存在一个 txt 文件中
【发布时间】:2017-04-26 15:28:17
【问题描述】:

我是使用 python 3 的真正初学者

我需要在一系列 txt 文件中减去两个不同的矩阵,然后在一个 txt 文件中得到所有结果。代码一直有效,直到我要求打印(它确实做到了),但是当我想保存“ncol= X.shape[1] indecerror: tuple index out of range”时,我不断收到错误消息

这里是代码

import sys, os

import numpy as np
from PIL import Image

newpath = "C:/Users/.../PycharmProjects/.../output/differenza"

os.makedirs(newpath)

for txt in range(162, 167):

    #fn = "C:/Users/.../PycharmProjects/.../output" + str(txt).zfill(0) + ".txt"

    v1 = np.loadtxt("C:/Users/.../PycharmProjects/.../output/result_628.txt")

    v2 = np.loadtxt("C:/Users/.../PycharmProjects/.../output/result_" + str(txt).zfill(1) + ".txt")

    v3 = v1 - v2

    picture = np.sum(v3)

    print("picture", picture)

    outfn = newpath + "/result_" + str(txt) + ".txt"

    np.savetxt("outfn", picture, fmt='%1.3f')

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您的 v3 可能只是一个标量值(由 numpy.sum() 返回)并且 numpy.savetxt() 需要一个类似数组的对象。

    您可以执行 np.savetxt("outfn", [picture,], fmt='%1.3f') 或 zipa 建议的操作。但是您确定要使用一个标量值写入多个文件吗?

    PS:我会将此放入评论中,但我还不允许:(

    【讨论】:

    • 不,实际上我希望它们都在一个文件中..但是现在我得到了不同的文件...xD
    • 然后简单地创建一个列表results=[] 并附加到它而不是用results.append(picture) 写入文件。然后在循环之后你可以做numpy.savetxt(filename, results)
    • 对不起,但它一直将数据保存在不同的文件中:(
    • 很难在没有看到您的代码的情况下说出原因。你试过zipas代码了吗?基本上和我建议的一样。
    • 它不起作用..我对 final = np.array() 有问题:\
    【解决方案2】:

    去:

    import sys, os
    import numpy as np
    from PIL import Image
    
    newpath = "C:/Users/.../PycharmProjects/.../output/differenza"
    
    os.makedirs(newpath)
    
    final = np.array()
    
    for txt in range(162, 167):
    
        #fn = "C:/Users/.../PycharmProjects/.../output" + str(txt).zfill(0) + ".txt"
    
        v1 = np.loadtxt("C:/Users/.../PycharmProjects/.../output/result_628.txt")
    
        v2 = np.loadtxt("C:/Users/.../PycharmProjects/.../output/result_" + str(txt).zfill(1) + ".txt")
    
        v3 = v1 - v2
    
        picture = np.sum(v3)
    
        print("picture", picture)
        np.append(final, picture)
    
    
    np.savetxt("outfn.txt", final, fmt='%1.3f')
    

    【讨论】:

    • 谢谢!只有一件事..我实际上想将我所有的标量值保存在一个文件中..对不起,我想我在解释我在寻找什么时弄得一团糟
    • 对不起,可能是我,但 final= np.array() 没有定义??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2020-04-02
    相关资源
    最近更新 更多