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

有些话、适合烂在心里 提交于 2019-12-10 14:57:15

问题


I need to write 3 numpy arrays into a txt file. The head of the file looks like that:

#Filexy
#time  operation1 operation2

The numpy arrays look like the following:

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

In the end, the .txt file should look like this (delimiter should be a tab):

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

I tried it with "numpy.savetxt" - but I did not get the format that I want.

Thank you very much for your help!


回答1:


I'm not sure what you tried, but you need to use the header parameter in np.savetxt. Also, you need to concatenate your arrays properly. The easiest way to do this is to use np.c_, which forces your 1D-arrays into 2D-arrays, and then concatenates them the way you expect.

>>> 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 now contains:

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

Also note the usage of fmt='%d' to get integer values in the output. savetxt will save as float by default, even for an integer array.

Regarding the delimiter, you just need to use the delimiter argument. It's not clear here, but there are, in fact, tabs between the columns. For instance, vim shows me tabs using dots:

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

Addendum:

If you want to add headers and add an extra line before the arrays, you are better off creating a custom header, complete with your own comment characters. Use the comment argument to prevent savetxt from adding extra #'s.

>>> 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='')

which produces

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



回答2:


Try this:

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


来源:https://stackoverflow.com/questions/39483774/how-to-write-numpy-arrays-to-txt-file-starting-at-a-certain-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!