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_
savetxt() Python's Numpy module provides a function to save numpy array to a txt file with custom delimiters and other custom options i.e. numpy. savetxt(fname, arr, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
Save an array to a text file. If the filename ends in . gz , the file is automatically saved in compressed gzip format.
Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.
The NumPy module savetxt() method is used to append the Numpy array at the end of the existing csv file with a single format pattern fmt = %s. We will open CSV file in append mode and call the savetxt() method to writes rows with header. Second call the savetxt() method to append the rows.
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.savetxt('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.
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.
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
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