[Numpy-discussion] structured array indexing oddity

Anthony Scopatz scopatz at gmail.com
Tue Mar 15 21:21:01 EDT 2011


Hi Matt,

Actually, based on what is happening under the covers I think this behavior
makes sense.

a['f2'] would in theory grab the whole column, and so 'f2' not existing is a
field error.

a[0] on the other hand grabs the first row from the full structured array
and treats this as (key, value) pair, much like a dictionary.  Thus when
'f2' doesn't exist in a[0]['f2'], it means it cannot find the key and is
therefore an IndexError.

I hope this helps
Be Well
Anthony

On Tue, Mar 15, 2011 at 7:24 PM, Matthew Brett <matthew.brett at gmail.com>wrote:

> Hi,
>
> I just wrote a short test for indexing into structured arrays with
> strings and found this:
>
> In [4]: a = np.zeros((1,), dtype=[('f1', 'i4')])
> In [5]: a['f1']
> Out[5]: array([0])
> In [6]: a['f2']  # not present -> error
> ---------------------------------------------------------------------------
> ValueError                                Traceback (most recent call last)
>
> /Users/mb312/<ipython console> in <module>()
>
> ValueError: field named f2 not found.
> In [7]: a[0]['f1'] # OK
> Out[7]: 0
> In [8]: a[0]['f2']
> ---------------------------------------------------------------------------
> IndexError                                Traceback (most recent call last)
>
> /Users/mb312/<ipython console> in <module>()
>
> IndexError: invalid index
>
> It seems odd to raise an 'IndexError' without a message about the
> field name in the second case, and a ValueError with a good message in
> the first.
>
> Do y'all agree?
>
> Matthew
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20110315/dd3773d5/attachment.html>


More information about the NumPy-Discussion mailing list