I am trying to read in data from a text file using numpy.loadtxt with the converters argument. I have a mixture of columns of ints and strings. The code is:
a, b, c, d, e = np.loadtxt(infile, delimiter = ',', usecols=(0, 2, 5, 8, 9), skiprows = 1,
unpack = True, converters = dict(zip((0, 2, 5, 8, 9), (int, float, float, int, int))))
The data are read in correctly and unpacked correctly, but all the variables (a, b, c, d, and e) end up as floats. Am I making a mistake in the converters syntax?
Edit trying answer
I tried using dtype = (int,float,float,int,int) as suggested by @joris as:
a,b,c,d,e = np.loadtxt(infile,delimiter = ',', usecols=(0,2,5,8,9), skiprows = 1, unpack = True, dtype = (int,float,float,int,int))
But I get the following error:
41 skiprows = 1,
42 unpack = True,
---> 43 dtype = (int,float,float,int,int))
44
45
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/npyio.pyc in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack)
665 try:
666 # Make sure we're dealing with a proper dtype
--> 667 dtype = np.dtype(dtype)
668 defconv = _getconv(dtype)
669
TypeError: data type not understood
WARNING: Failure executing file: <forward_NDMMF.py>
I am using NumPy v. 1.5.1.
For specifying the type of the different columns, you can use the argument
dtypeinstead ofconverters:EDIT:
Apparantly, this type of
dtypespecification does not seem to work withloadtxt, but it works withgenfromtxt(Does anybody know why this does not work work withloadtxt, or is this one of the extra capabilities ofgenfromtxt?)If you want to use
loadtxt, a structured dtype specification with tuples works, like[('f0', int), ('f1', float)]instead of(int, float)But there is another problem. When working with such structured dtypes, and so structured arrays (different types for different columns), the
unpackdoes not seem to work. At least with a simple example I tried. But that could be a bug that is already solved: http://projects.scipy.org/numpy/ticket/1458 (but for that, you have to upgrade to even 1.6).