[Numpy-discussion] dumb structured arrays question

David Warde-Farley dwf at cs.toronto.edu
Thu Sep 17 18:27:18 EDT 2009


On 17-Sep-09, at 6:18 PM, Erin Sheldon wrote:
>
> You can just view it differently:
>
> In [4]: x=numpy.zeros(3,dtype=[('field1','S5'),('field2','f4'), 
> ('field3','f4'),('field4','f4')])
>
> In [5]: x
> Out[5]:
> array([('', 0.0, 0.0, 0.0), ('', 0.0, 0.0, 0.0), ('', 0.0, 0.0, 0.0)],
>      dtype=[('field1', '|S5'), ('field2', '<f4'), ('field3', '<f4'),
> ('field4', '<f4')])
>
> In [6]: dt=numpy.dtype([('field1','S5'),('compound','3f4')])
>
> In [7]: x.view(dt)
> Out[7]:
> array([('', [0.0, 0.0, 0.0]), ('', [0.0, 0.0, 0.0]), ('', [0.0, 0.0,  
> 0.0])],
>      dtype=[('field1', '|S5'), ('compound', '<f4', 3)])
>
> In [8]: x.view(dt)['compound']
> Out[8]:
> array([[ 0.,  0.,  0.],
>       [ 0.,  0.,  0.],
>       [ 0.,  0.,  0.]], dtype=float32)

Thanks, that's immensely useful. Didn't know about .view().

David



More information about the NumPy-Discussion mailing list