[SciPy-User] best way to convert a structured array to a float view (again)
Skipper Seabold
jsseabold at gmail.com
Fri Jun 4 11:55:48 EDT 2010
Say I have the following arrays that I want to view as/cast to plain
ndarrays with float dtype
import numpy as np
arr = np.array([(24,),(24,),(24,),(24,),(24,)], dtype=[("var1",int)])
arr2 = np.array([(24,4.5),(24,4.5),(24,4.5),(24,4.5),(24,4.5)],
dtype=[("var1",int),("var2",float)])
What I really want to be able to do is something like
arr.view(float)
or
arr2.view((float,2))
But I realize that I can't do this because of how the structs are
defined in memory. So my question is, is this the best (cheapest,
easiest) way to get arr or arr2 as all floats.
arr3 = np.zeros(len(arr), dtype=float)
arr3[:] = arr.view(int)
or
arr4 = np.zeros(len(arr2),
dtype=zip(arr2.dtype.names,['float']*len(arr2.dtype.names)))
arr4[:] = arr2[:]
arr5 = arr4.view((float,len(arr4.dtype.names)))
So now I have arr3 and arr5. I need this to be rather general (can
ignore strings and object types for now), so that's the reason for the
approach I'm taking here.
Thanks,
Skipper
More information about the SciPy-User
mailing list