[Numpy-discussion] recarray field access asymmetry
Wed Feb 15 02:07:25 CST 2012
On Wednesday, February 15, 2012, David Gowers (kampu) <firstname.lastname@example.org>
> Hi all,
> This email is about the difference, given a recarray 'arr',
> and B)
> Specifically, form A returns the 0-th x value, whereas form B raises
> Some code demonstrating this:
>>>> arr = np.zeros((4,), dtype = [('foo',[('x','H'),('y','H')])])
>>>> a2 = arr.view (np.recarray)
> rec.array([(0, 0), (0, 0), (0, 0), (0, 0)],
> dtype=[('x', '<u2'), ('y', '<u2')])
> array([0, 0, 0, 0], dtype=uint16)
> (0, 0)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'numpy.void' object has no attribute 'x'
> (similarly, ``a2.foo`` raises an identical AttributeError)
> This is obstructive, particularly since ``a2.foo.x`` is the more
> logical grouping than ``a2.foo.x`` -- we want the x field of item 0
> in foo, not the 0th x-value in foo.
> I see this issue has come up previously...
> The solution proposed by Travis in that email:
> ('arr.view(dtype=(np.record, b.dtype), type=np.recarray)')
> is ineffective with current versions of NumPy; the result is exactly
> the same as if you had not done it at all.
> I've tried various other methods including subclassing recarray and
> overriding __getitem__ and __getattribute__, with no success.
> My question is, is there a way to resolve this so that ``a2.foo.x``
> does actually do what you'd expect it to?
Rather than recarrays, I just use structured arrays like so:
A = np.array([(0, 0), (0, 0), (0, 0), (0, 0)],
dtype=[('x', '<u2'), ('y', '<u2')])
I can then do:
This allows me to slice and access the data any way I want. I have even
been able to use this dictionary idiom to format strings and such.
Does that help?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion