On Tue, Aug 2, 2011 at 9:09 AM, Brett Olsen <brett.ol...@gmail.com> wrote: > On Tue, Aug 2, 2011 at 9:44 AM, Jeremy Conlin <jlcon...@gmail.com> wrote: >> I am trying to create a numpy array from some text I'm reading from a >> file. Ideally, I'd like to create a structured array with the first >> element as an int and the remaining as floats. I'm currently >> unsuccessful in my attempts. I've copied a simple script below that >> shows what I've done and the wrong output. Can someone please show me >> what is happening? >> >> I'm using numpy version 1.5.1 under Python 2.7.1 on a Mac running Snow >> Leopard. >> >> Thanks, >> Jeremy > > I'd use numpy.loadtxt: > > In [1]: import numpy, StringIO > > In [2]: l = ' 32000 7.89131E-01 8.05999E-03 3.88222E+03' > > In [3]: tfc_dtype = numpy.dtype([('nps', 'u8'), ('t', 'f8'), ('e', > 'f8'), ('fom', 'f8')]) > > In [4]: input = StringIO.StringIO(l) > > In [5]: numpy.loadtxt(input, dtype=tfc_dtype) > Out[5]: > array((32000L, 0.78913100000000003, 0.0080599899999999995, > 3882.2199999999998), > dtype=[('nps', '<u8'), ('t', '<f8'), ('e', '<f8'), ('fom', '<f8')]) > > In [6]: input.close() > > In [7]: input = StringIO.StringIO(l) > > In [8]: numpy.loadtxt(input) > Out[8]: > array([ 3.20000000e+04, 7.89131000e-01, 8.05999000e-03, > 3.88222000e+03]) > > In [9]: input.close() > > If you're reading from a file you can replace the StringIO objects > with file objects.
Thanks, Brett. Using StringIO and numpy.loadtxt worked great. I'm still curious why what I was doing didn't work. Everything I can see indicates it should work. Jeremy _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion