[Numpy-discussion] Record arrays, nesting, and assignment
Robert Kern
robert.kern@gmail....
Wed Jul 15 14:46:32 CDT 2009
On Wed, Jul 15, 2009 at 14:38, Pauli Virtanen<pav+sp@iki.fi> wrote:
> On 2009-07-15, Robert Kern <robert.kern@gmail.com> wrote:
>> 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')
>>
> [clip]
>>
>> 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.
>
> But then, why does it alter the first element of the sub-array?
> This seems like a bug...
Hmm, it's worse than I feared. The scalars are indeed views; it's just
that the assignment to an array field is buggy. But then, I don't
think the records should be mutable at all.
In [18]: dt = dtype([('foo', float, 2), ('bar', int)])
In [19]: a = zeros(3, dt)
In [20]: a
Out[20]:
array([([0.0, 0.0], 0), ([0.0, 0.0], 0), ([0.0, 0.0], 0)],
dtype=[('foo', '<f8', 2), ('bar', '<i4')])
In [21]: a0 = a[0]
In [22]: a0['bar'] = 3
In [23]: a
Out[23]:
array([([0.0, 0.0], 3), ([0.0, 0.0], 0), ([0.0, 0.0], 0)],
dtype=[('foo', '<f8', 2), ('bar', '<i4')])
--
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