Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.savetxt Problems with 1D array writing

Tags:

python

numpy

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

like image 387
Matthew Brookhart Avatar asked Feb 02 '23 17:02

Matthew Brookhart


2 Answers

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.

like image 143
Sven Marnach Avatar answered Feb 05 '23 16:02

Sven Marnach


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'
like image 21
jterrace Avatar answered Feb 05 '23 15:02

jterrace