0

I need to convert a Python list with mixed type (integers and floats) to a Numpy structured array with certain column names.

I have tried the following code but for some reason I cant see it doesn't work.

import numpy as np
lmtype = [('el','intp',1),  ('n1','intp',1),  ('n2','intp',1),  ('n3','float64',1),
          ('n4','float64',1),  ('n5','float64',1),  ('n6','float64',1),  ('n7','float64',1),
          ('n8','float64',1),  ('n9','float64',1),  ('n10','float64',1),  ('n11','float64',1)]
LAMI = np.zeros(5, dtype=lmtype)
linea = ['1', '2', '3', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0']
for idx, la in enumerate(LAMI):
    lineanum = ([ int(j) for j in linea[0:3] ] + [float(i) for i in linea[3:12] ] )
    print lineanum
    LAMI[idx] = np.array( lineanum )

The code runs, but look what LAMI has inside:

>>> LAMI[0]
(0, 1072693248, 0, 5.304989477e-315, 5.307579804e-315, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
1
  • np.array( lineanum ) makes a normal array, and casts the ints of the first three elements into a float to make all the elements the same type. And then the cast to LAMI fails. Commented Mar 24, 2015 at 0:15

1 Answer 1

2

Try:

LAMI[idx] = tuple( lineanum )

Tuples are the normal way to assign to a record (row) of a structured array. They can hold mixed types, just like the structured element.

np.array(lineanum) is all float. LAMI[idx] = np.array( lineanum ) just copies the buffer full of floats to a segment of the LAMI buffer. I'm a little surprised that it permits this copy; it must be doing some sort of 'copy only as much as fits'. LAMI.itemsize is 84, while the total length of np.array(lineanum) is 12*8=96.

LAMI[0]=np.array(lineanum, dtype=int) # or better
LAMI[0]=np.array(lineanum[:3], type=int)

would also work, since the only nonzero values are those 1st 3 which are suppposed to be ints.

2
  • Great @hpaulj !!! The first solutions works perfectly... Now I see... the structured array is a one dimensional array of tuples, is this ok? Thanks very much for your quick answer! Commented Mar 24, 2015 at 2:12
  • Technically it isn't an array of tuples, since the bytes are packed, as opposed to being pointers. But it is displayed as tuples, and .tolist() will produce a list of tuples. So it is useful to think along those lines. Commented Mar 24, 2015 at 2:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.