【问题标题】:How to write numpy arrays to .txt file, starting at a certain line?如何从某一行开始将 numpy 数组写入 .txt 文件?
【发布时间】:2017-01-21 20:47:35
【问题描述】:

我需要将 3 个 numpy 数组写入一个 txt 文件。文件头是这样的:

#Filexy
#time  operation1 operation2

numpy 数组如下所示:

time = np.array([0,60,120,180,...])
operation1 = np.array([12,23,68,26,...)]
operation2 = np.array([100,123,203,301,...)]

最后,.txt 文件应该是这样的(分隔符应该是一个制表符):

#Filexy
#time  operation1 operation2
0   12   100
60  23    123
120  68   203
180  26   301
..  ...   ...

我尝试使用“numpy.savetxt” - 但我没有得到我想要的格式。

非常感谢您的帮助!

【问题讨论】:

    标签: python numpy writetofile


    【解决方案1】:

    我不确定您尝试了什么,但您需要使用np.savetxt 中的header 参数。此外,您需要正确连接数组。最简单的方法是使用np.c_,它将您的一维数组强制转换为二维数组,然后按照您期望的方式将它们连接起来。

    >>> time = np.array([0,60,120,180])
    >>> operation1 = np.array([12,23,68,26])
    >>> operation2 = np.array([100,123,203,301])
    >>> np.savetxt('example.txt', np.c_[time, operation1, operation2],
                   header='Filexy\ntime  operation1 operation2', fmt='%d',
                   delimiter='\t')
    

    example.txt 现在包含:

    # Filexy
    # time  operation1 operation2
    0   12  100
    60  23  123
    120 68  203
    180 26  301
    

    还要注意使用fmt='%d' 在输出中获取整数值。 savetxt 默认保存为浮点数,即使是整数数组。

    关于分隔符,您只需要使用delimiter 参数即可。这里不清楚,但实际上列之间有选项卡。例如,vim 使用点向我显示标签:

    # Filexy
    # time  operation1 operation2
    0·  12· 100
    60· 23· 123
    120·68· 203
    180·26· 301
    

    附录:

    如果你想添加标题并且在数组之前添加一个额外的行,你最好创建一个自定义标题,并用你自己的注释字符完成。使用comment 参数来防止savetxt 添加额外的#

    >>> extra_text = 'Answer to life, the universe and everything = 42'
    >>> header = '# Filexy\n# time operation1 operation2\n' + extra_text
    >>> np.savetxt('example.txt', np.c_[time, operation1, operation2],     
                   header=header, fmt='%d', delimiter='\t', comments='')
    

    产生

    # Filexy
    # time operation1 operation2
    Answer to life, the universe and everything = 42
    0   12  100
    60  23  123
    120 68  203
    180 26  301
    

    【讨论】:

    • 别忘了delimiter='\t'
    • 非常感谢!还有一件事——>我怎么能在第三行(在数组开始之前)写一行不以 # 开头的行(在我的情况下它只是一个数字)
    • 再次感谢您-我尝试了您的附录-但我错过了 extra_num :)。如果可能,代码应如下所示: 第一行 "#Filexy; 第二行 "#time operation1 operation2;第三行“42(不带#);第四行--end..:数组。非常感谢您帮助我!
    【解决方案2】:

    试试这个:

    f = open(name_of_the_file, "a")
    np.savetxt(f, data, newline='\n')
    f.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2018-07-09
      • 2017-07-15
      • 2014-08-30
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多