Matias Matias - 2 months ago 9
Python Question

Write numpy arrays to .txt file, starting at a certain line

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!

Answer

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
Comments