Matthew Brookhart
Matthew Brookhart

Reputation: 101

numpy.savetxt Problems with 1D array writing

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

Upvotes: 10

Views: 9616

Answers (2)

jterrace
jterrace

Reputation: 67063

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'

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601401

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.

Upvotes: 13

Related Questions