如何从某一行开始将 numpy 数组写入 .txt 文件?

How to write numpy arrays to .txt file, starting at a certain line?

我需要将 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" 试过了 - 但我没有得到我想要的格式。

非常感谢您的帮助!

试试这个:

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

我不确定您尝试了什么,但您需要在 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

附录:

如果你想添加 headers 在数组之前添加额外的一行,你最好创建一个自定义 header,完成你自己的评论字符。使用 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