[Numpy-discussion] Getting an item in an array with its coordinates given by another array

Christian K. ckkart@hoc....
Sun Oct 28 22:21:34 CDT 2007


Matthieu Brucher <matthieu.brucher <at> gmail.com> writes:

> 
> 
> Little correction, only c[(2,3)] gives me what I expect, not c[[2,3]], which
> is even stranger.

c[(2,3)] is the same as c[2,3] and obviously works as you expected.
c[[2,3]] is refered to as 'advanced indexing' in the numpy book.
It will return elements 2 and 3 along the first dimension. To get what you
want, you need to put it like this:

c[[2],[3]]

In [118]: c = N.arange(0.,3*4*5).reshape((3,4,5))

In [119]: c[[2],[3]]

Out[119]: array([[ 55.,  56.,  57.,  58.,  59.]])

This does not work however using a ndarray holding the indices. 

In [120]: ind = N.array([[2],[3]])

In [121]: c[ind]
---------------------------------------------------------------------------
<type 'exceptions.IndexError'>            Traceback (most recent call last)

/media/hda6/home/ck/<ipython console> in <module>()

<type 'exceptions.IndexError'>: index (3) out of range (0<=index<=2) in
dimension 0

so you have to convert it to a list before:

In [122]: c[ind.tolist()]
Out[122]: array([[ 55.,  56.,  57.,  58.,  59.]])

Christian



More information about the Numpy-discussion mailing list