using numpy dtype with loadtxt

linux
python
Published

March 3, 2010

Let’s say you want to read a text file like this:


#filename start end
fdsafda.fits 23143214 23143214
safdsafafds.fits 21423 23423432





you can use dtype to create a custom array, which is very flexible as you can work by row or columns with strings and floats in the same array:
dt=np.dtype({‘names’:[‘filename’,‘start’,‘end’],‘formats’:[‘S100’,np.float,np.float]})
[I tried also using np.str instead of S100 without success, anyone knows why?]
then give this as input to loadtxt to load the file and create the array.
a = np.loadtxt(open(‘yourfile.txt’),dtype=dt)
so each element is:
(‘dsafsadfsadf.fits’, 1.6287776249537126e+18, 1.6290301584937428e+18)

but you can get the array of start or end times using:
a[‘start’]