[Numpy-discussion] Record arrays, nesting, and assignment

Robert Kern robert.kern@gmail....
Wed Jul 15 14:28:40 CDT 2009


On Wed, Jul 15, 2009 at 14:19, Vebjorn Ljosa<vebjorn@ljosa.com> wrote:
> Suppose I have a record array where one of the fields is a nested array:
>
>  >>> from numpy import *
>  >>> desc = dtype([('point', 'i4', 3), ('unimportant', 'S3')])
>  >>> a = array([((1,2,3), 'foo'), ((7,8,9), 'bar')], dtype=desc)
>  >>> a
> array([([1, 2, 3], 'foo'), ([7, 8, 9], 'bar')],
>      dtype=[('point', '<i4', 3), ('unimportant', '|S3')])
>  >>> a[0]
> ([1, 2, 3], 'foo')
>
> If I try to assign to a[0]['point'], it only works partially:
>
>  >>> a[0]['point'] = array([4, 5, 6])
>  >>> a[0]
> ([4, 2, 3], 'foo')
>
> However, if I assign to a['point'][0], it works:
>
>  >>> a['point'][0] = array([10, 11, 12])
>  >>> a[0]
> ([10, 11, 12], 'foo')
>
> I should obviously remember to do it the second way ... but why does
> the first way not work?

Generally, scalars are never views. a[0] pulls out a record scalar.
Assigning into that scalar does not affect the original memory.
a['point'] creates an array that is a view and assigning to the [0]
element of that array modifies the original memory.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the NumPy-Discussion mailing list