[Numpy-discussion] n-dimensional array indexing question

Nathan Bell wnbell@gmail....
Sat Nov 8 17:44:23 CST 2008


On Sat, Nov 8, 2008 at 5:35 PM, dmitrey <dmitrey.kroshko@scipy.org> wrote:
> hi all,
> I have array A, A.ndim = n, and 1-dimensional array B of length n.
> How can I get element of A with coords B[0],...,B[n-1]?
> i.e. A[B[0], B[1], ..., B[n-1])
>
> A, B, n are not known till execution time, and can have unpredictable
> lengths (still n is usually small, no more than 4-5).
>
> I have tried via ix_ but haven't succeeded yet.
>

There's probably a better way, but tuple(B) works:

In [1]: from numpy import *

In [2]: A = arange(8).reshape(2,2,2)

In [3]: A
Out[3]:
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

In [4]: B = array([0,1,0])

In [5]: A[tuple(B)]
Out[5]: 2


-- 
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/


More information about the Numpy-discussion mailing list