Daniel Forsman Daniel Forsman - 1 month ago 9
Python Question

Flatten tuple containing numpy array to numpy array

So I used

operator.attrgetter
to try to rip an array class into a numpy array by
tupleList=map(attrgetter(*inNames),inClass)
and ended up with something like this for
tupleList[0]


(1, array([0.0, 0.0, 0.0, 0.0], 'f'), 1)


I'd like to turn that into a numpy array (specifically a structured array, but I can work that out) that looks like this

array([1, 0.0, 0.0, 0.0, 0.0, 1], dtype=(('id', 'i8'), . . . .)])


Unfortunately,
np.asArray(tupleList[0])
and
np.asAnyArray(tupleList[0])
don't work and I get

ValueError: setting an array element with a sequence


Is there a way around this? Currently fighting my IT division to get pandas, but don't have it right now. I assume that would that help?

Answer

Use no.hstack in order to integrate your tuple :

In [106]: foo = (1, np.array([0.0, 0.0, 0.0, 0.0], 'f'), 1)

In [107]: np.hstack(foo)
Out[107]: array([ 1.,  0.,  0.,  0.,  0.,  1.])
Comments