[Numpy-discussion] Structured array dtype

Stéfan van der Walt stefan@sun.ac...
Sat Aug 31 00:51:36 CDT 2013


Hi Nicolas

On Fri, 30 Aug 2013 17:26:51 +0200, Nicolas Rougier wrote:
> >>> Z = np.zeros(10, [('a', np.float32, 3), ('b', np.float32, 4)])
> 
> >>> Z['a'].dtype
> dtype('float32')
> 
> >>> Z.dtype['a']
> dtype(('<f4', (3,)))
> 
> 
> Does that mean that dtype['a'] is the dtype of field 'a' when in Z, while Z['a'].dtype is the dtype of field 'a' when "extracted" or my way of thinking is totally wrong ?

Apologies if this is a duplicate response; I'm sending it offline.

In case 1, you are indexing into the array, and querying its dtype.  In case
two, you are indexing into a dtype.

I.e., in case two, you are doing this:

In [18]: dtype = np.dtype([('a', float, 3), ('b', int)])

In [19]: dtype['a']
Out[19]: dtype(('<f8', (3,)))

> What bothers me the most is that I cannot do:
> 
> >>> Z['a'].view(Z.dtype['a'])
> ValueError: new type not compatible with array.

That's quite a tricky operation to perform, since it has to take into account
the underlying strides of the old array as well as calculate a shape for the
new array.  It should be possible to make it work using something similar to
`np.lib.stride_tricks.as_strided`, but my quick attempt failed because of the
following:

In [13]: class Foo:
    __array_interface__ = Z.__array_interface__
   ....:

In [14]: f = Foo()

In [15]: np.asarray(f)
Out[15]:
array([, ,
       , ,
       , ,
       , ,
       , ],
      dtype='|V28')

This does not seem right.

Stéfan



More information about the NumPy-Discussion mailing list