开发者

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 s开发者_运维技巧avetxt 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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜