tags:

views:

653

answers:

3

Hi,

Can someone indicate what I am doing wrong here?

import numpy as np

a = np.array([1,2,3,4,5],dtype=int)
b = np.array(['a','b','c','d','e'],dtype='|S1')

np.savetxt('test.txt',zip(a,b),fmt="%i %s")

The output is:

Traceback (most recent call last):
  File "loadtxt.py", line 6, in <module>
    np.savetxt('test.txt',zip(a,b),fmt="%i %s")
  File "/Users/tom/Library/Python/2.6/site-packages/numpy/lib/io.py", line 785, in savetxt
    fh.write(format % tuple(row) + '\n')
TypeError: %d format: a number is required, not numpy.string_
A: 

I think the problem you are having is that you are passing tuples through the formating string and it can't interpret the tuple with %i. Try using fmt="%s", assuming this is what you are looking for as the output:

1 a
2 b
3 c
4 d
5 e
dwelch
that's just wrong. `fmt="%s"` works for entirely different reasons, `fmt="%s %s"` works too, btw.
SilentGhost
You're right, as soon as I posted I realized it worked, but not for the reason I thought. My bad. The post by SilentGhost is much better. Thanks.
dwelch
+3  A: 

You need to construct you array differently:

z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')])
np.savetext('test.txt', z, fmt='%i %s')

when you're passing a sequence, savetext performs asarray(sequence) call and resulting array is of type |S4, that is all elements are strings! that's why you see this error.

SilentGhost
A: 

If you want to save a CSV file you can also use the function rec2csv (included in matplotlib.mlab)

>>> from matplotlib.mlab import rec2csv
>>> rec = array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)])
>>> rec = array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('x', int), ('y', str)])
>>> rec2csv(rec, 'recordfile.txt', delimiter=' ')

hopefully, one day pylab's developers will implement a decent support to writing csv files.

dalloliogm