[Numpy-discussion] Newbie indexing question [fancy indexing in nD]
Angus McMorland
a.mcmorland at auckland.ac.nz
Fri Apr 7 00:30:07 EDT 2006
Hi again.
Thanks, everyone, for your quick replies.
Travis Oliphant wrote:
> 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.
Great. Turns out I wasn't too far off then. I've written a quick
function of my own that extends the fancy indexing to nD:
def fancy_index_nd(ar, ind):
evList = ['ar[']
for i in range(len(ar.shape)):
evList = evList + [' ind[...,%d]' % i]
if i < len(ar.shape) - 1:
evList = evList + [","]
evList = evList + [' ]']
return eval(''.join(evList))
1) Am I missing a simpler way to extend the fancy-indexing to
n-dimensions? If not...
2) this seems (conceptually) that it might be a little faster than the
routines that have to calculate a flat index. Hopefully it could be of
use to people. Any thoughts?
Cheers,
Angus
--
Angus McMorland
email a.mcmorland at auckland.ac.nz
mobile +64-21-155-4906
PhD Student, Neurophysiology / Multiphoton & Confocal Imaging
Physiology, University of Auckland
phone +64-9-3737-599 x89707
Armourer, Auckland University Fencing
Secretary, Fencing North Inc.
More information about the NumPy-Discussion
mailing list