Reputation: 172
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)
Upvotes: 0
Views: 904
Reputation: 231345
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.
Upvotes: 2