[SciPy-User] best way to convert a structured array to a float view (again)

Vincent Davis vincent at vincentdavis.net
Fri Jun 4 15:38:24 EDT 2010


On Fri, Jun 4, 2010 at 9:55 AM, Skipper Seabold <jsseabold at gmail.com> wrote:
> 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)

I am going to do some timing but this looks promising. Glad to know I
am not the onlyone that think going between data types is a hassel.

arr2 = np.array([(24,4.5),(24,4.5),(24,4.5),(24,4.5),(24,4.5)],
                dtype=[("var1",int),("var2",float)])
>>> arr2.dtype=float
>>> arr2
array([  1.18575755e-322,   4.50000000e+000,   1.18575755e-322,
         4.50000000e+000,   1.18575755e-322,   4.50000000e+000,
         1.18575755e-322,   4.50000000e+000,   1.18575755e-322,
         4.50000000e+000])

Of course if you want to leave arr2 untouched you need some type of copy.

Vincent


>
> 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
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>



More information about the SciPy-User mailing list