【问题标题】:Python: Write array to file row by rowPython:将数组逐行写入文件
【发布时间】:2017-06-12 02:31:30
【问题描述】:

我有一个文件,内容为

18
21
24
27
30

还有数组

[[ 1  6 11]
 [ 2  7 12]
 [ 3  8 13]
 [ 4  9 14]
 [ 5 10 15]]

如何将此数组写入文件,以便每一行都与适当的行相对应,例如:

18    1  6 11
21    2  7 12
24    3  8 13
27    4  9 14
30    5 10 15

我已经使用了这段代码,但它并没有按照我的意愿编写代码。代码:

import numpy as np

    ourlist = []
    for i in range(1, 16):
        ourlist.append(i)


    mydata = np.matrix([ourlist])
    array_from_list=(mydata.reshape(3, 5))
    x_transpose = (np.transpose(array_from_list))   # the array above

    with open('5rows.txt','a') as f:                #the file containing numbers
     for elements in x_transpose:
         f.write(str(elements))
         f.write('\n')

它改为将元素写入行尾。如果可能的话,你能告诉我我该怎么做吗?非常感谢您的帮助!

【问题讨论】:

  • 您是否尝试过使用数据框?它可能会让你的事情变得更容易。
  • 所以文件中的第一列是行的总和。这不是你放的吗?我的回答假设需要一个水平追加,但也许你是先写总和,然后尝试在它旁边写矩阵。这不是解决问题的好方法。也许我太自以为是了,但我想我应该对你未来的利益感到好奇。

标签: python file numpy string-formatting


【解决方案1】:

np.savetxt 写入一个 csv 文件。在这种情况下,诀窍是将两个数组/列表组合成一个复合数组,然后根据需要对其进行格式化:

In [100]: mydata = np.arange(1,16).reshape(3,5)
In [101]: mydata
Out[101]: 
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])
In [102]: mydata = np.arange(1,16).reshape(3,5).T
In [103]: mydata
Out[103]: 
array([[ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14],
       [ 5, 10, 15]])
In [104]: elements = np.arange(18,31,3)
In [105]: elements
Out[105]: array([18, 21, 24, 27, 30])
In [106]: arr = np.column_stack((elements, mydata))
In [107]: arr
Out[107]: 
array([[18,  1,  6, 11],
       [21,  2,  7, 12],
       [24,  3,  8, 13],
       [27,  4,  9, 14],
       [30,  5, 10, 15]])
In [108]: np.savetxt('test.txt',arr, fmt='%2d   %3d %3d %3d')
In [109]: cat test.txt
18     1   6  11
21     2   7  12
24     3   8  13
27     4   9  14
30     5  10  15

相当于我可以zip 到两个数组;将 row 值组合成一个元组,并格式化:

In [112]: for e, d in zip(elements, mydata):
     ...:     ed = (e,)+tuple(d)
     ...:     print('%2d   %3d %3d %3d'%ed)
              # print(('%d  '%e) + ' '.join(['%3d']*3)%tuple(d))
     ...:     
18     1   6  11
21     2   7  12
24     3   8  13
27     4   9  14
30     5  10  15

我正在使用print,但您可以将其切换为文件写入。

【讨论】:

    【解决方案2】:

    下面的代码可能会解决您的问题,尽管它的性能不是很好。您或许可以改进解决方案以更好地满足您的需求。

    import numpy as np
    
    ourlist = []
    
    for i in range(1, 16):
        ourlist.append(i)
    
    
    mydata = np.matrix([ourlist])
    array_from_list=(mydata.reshape(3, 5))
    x_transpose = (np.transpose(array_from_list))
    
    with open('file.txt', 'r') as f:
        lines = f.readlines()
    
    with open('file.txt', 'w') as f:
        i = 0
        for line in lines:
            f.write(str(int(line)) + "  " + str(x_transpose[i])[1:-1][1:-1] + "\n")
            i+=1
    

    【讨论】:

      【解决方案3】:

      我认为您误解了“附加”的含义。当您将数据附加到文件时,这意味着垂直附加:将内容添加到文件的末尾。如果要进行水平追加,则必须首先读取数据,然后将所有内容写回。

      import numpy as np
      
      mydata = np.matrix(list(range(1, 16)))
      array_from_list=(mydata.reshape(3, 5))
      x_transpose = (np.transpose(array_from_list))   # the array above
      
      with open('5rows.txt','r') as f:
          lines = list(f)
      with open('5rows.txt','w') as f:
          for existing, new in zip(lines[:16], x_transpose):
              f.write('{}\t{}\n'.format(existing, '\t'.join(new)))
      

      【讨论】:

        猜你喜欢
        • 2017-05-21
        • 1970-01-01
        • 2018-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多