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

时间:2016-09-14 06:27:06

标签: python numpy writetofile

我需要将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 个答案:

答案 0 :(得分:4)

我不确定您尝试了什么,但您需要使用header中的np.savetxt参数。此外,您需要正确连接数组。最简单的方法是使用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将保存为float,即使对于整数数组也是如此。

关于分隔符,您只需要使用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 :(得分:0)

试试这个:

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