[Numpy-discussion] Finding many ways to incorrectly create a numpy array. Please advice

Jeremy Conlin jlconlin at gmail.com
Tue Aug 2 10:44:26 EDT 2011


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


import numpy

l = '      32000  7.89131E-01  8.05999E-03  3.88222E+03'
tfc_dtype = numpy.dtype([('nps', 'u8'), ('t', 'f8'), ('e', 'f8'),
('fom', 'f8')])

m = numpy.fromstring(l, sep=' ')
print("\nm: {}".format(m))

# Next line gives:
# ValueError: don't know how to read character strings with that array type
#n = numpy.fromstring(l, dtype=tfc_dtype, sep=' ')
#print("\nn: {}".format(n))

words = l.split()
o = numpy.array(words, dtype='f8')
print("\no: {}".format(o))

# Next line(s) gives bad answer
p = numpy.array(words, dtype=tfc_dtype)
print("\np: {}".format(p))

nps = int(words[0])
t = float(words[1])
e = float(words[2])
fom = float(words[3])
a = [nps, t, e, fom]

# Next line(s) converts int to float in first element
r = numpy.array(a)
print("\nr: {}".format(r))

# Next line gives:
# TypeError: expected a readable buffer object
# s = numpy.array(a, dtype=tfc_dtype)
# print("\ns: {}".format(s))



More information about the NumPy-Discussion mailing list