[Numpy-discussion] Newbie indexing question and print order
Travis Oliphant
oliphant.travis at ieee.org
Thu Apr 6 03:40:05 CDT 2006
amcmorl wrote:
> Hi all,
>
> I'm having a bit of trouble getting my head around numpy's indexing
> capabilities. A quick summary of the problem is that I want to
> lookup/index in nD from a second array of rank n+1, such that the last
> (or first, I guess) dimension contains the lookup co-ordinates for the
> value to extract from the first array. Here's a 2D (3,3) example:
>
> In [12]:print ar
> [[ 0.15 0.75 0.2 ]
> [ 0.82 0.5 0.77]
> [ 0.21 0.91 0.59]]
>
> In [24]:print inds
> [[[1 1]
> [1 1]
> [2 1]]
>
> [[2 2]
> [0 0]
> [1 0]]
>
> [[1 1]
> [0 0]
> [2 1]]]
>
> then somehow return the array (barring me making any row/column errors):
> In [26]: c = ar.somefancyindexingroutinehere(inds)
>
You can do this with "fancy-indexing". Obviously it is going to take
some time for people to get used to this idea as none of the responses
yet suggest it.
But the following works.
c = ar[inds[...,0],inds[...,1]]
gives the desired effect.
Thus, your simple description c[x,y] = ar[inds[x,y,0],inds[x,y,1]] is a
text-book description of what fancy-indexing does.
Best regards,
-Travis
> In [26]:print c
> [[ 0.5 0.5 0.91]
> [ 0.59 0.15 0.82]
> [ 0.5 0.15 0.91]]
>
> i.e. c[x,y] = a[ inds[x,y,0], inds[x,y,1] ]
>
> Any suggestions? It looks like it should be relatively simple using
> 'put' or 'take' or 'fetch' or 'sit' or something like that, but I'm not
> getting it.
>
> While I'm here, can someone help me understand the rationale behind
> 'print' printing row, column (i.e. a[0,1] = 0.75 in the above example
> rather than x, y (=column, row; in which case 0.75 would be in the first
> column and second row), which seems to me to be more intuitive.
>
> I'm really enjoying getting into numpy - I can see it'll be
> simpler/faster coding than my previous environments, despite me not
> knowing my way at the moment, and that python has better opportunities
> for extensibility. So, many thanks for your great work.
>
More information about the Numpy-discussion
mailing list