如何将numpy数组写入.txt文件,从特定行开始?

5

我需要将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",但我没有得到想要的格式。
非常感谢您的帮助!
2个回答

4

我不确定你尝试了什么,但是你需要在np.savetxt中使用header参数。此外,你需要正确地连接你的数组。最简单的方法是使用np.c_,它将你的1D数组强制转换为2D数组,并按照你的期望方式连接它们。

>>> 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

1
请不要忘记设置分隔符为 delimiter='\t' - juanpa.arrivillaga
非常感谢!还有一个问题 --> 在数组开始前的第三行,我该如何写一行不以 # 开头的代码呢?(在我的情况下,它将只是一个数字) - Matias
再次感谢您 - 我尝试了您的补充说明 - 但我错过了 extra_num :). 如果可能,代码应该像这样:第一行 "#Filexy; 第二行 "#time operation1 operation2; 第三行 "42(没有 #); 第四行--end..: 数组。非常感谢您的帮助! - Matias
请参见http://stackoverflow.com/questions/39487605/how-to-write-numpy-arrays-to-txt-file-starting-at-a-certain-line-numpy-versio :) 谢谢 - Matias

0

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接