I'm trying to use numpy's savetxt
function to generate a bunch of files as inputs for another piece of software.
I'm trying to write an array of the form:
a=np.array([1,2,3,4,...])
a.shape=>(1,n)
to a text file with the formatting 1,2,3,4,...
when I enter the command
np.savetxt('test.csv',a,fmt='%d',delimiter=',')
I get a file that looks like:
1
2
3
4
...
savetxt
works as I would expect for a 2D array, but I can't get all of the values for a 1D array onto a single line
Any suggestions?
Thanks
EDIT:
I solved the problem. Using np.atleast_2d(a)
as the input to savetxt forces savetxt to write the array as a row, not a column
There are different ways to fix this. The one closest to your current approach is:
np.savetxt('test.csv', a[None], fmt='%d', delimiter=',')
i.e. add the slicing [None]
to your array to make it two-dimensional with only a single line.
If you only want to save a 1D array, it's actually a lot faster to use this method:
>>> x = numpy.array([0,1,2,3,4,5])
>>> ','.join(map(str, x.tolist()))
'0,1,2,3,4,5'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With