Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexing multidimensional arrays with an array

I have a multidimensional NumPy array:

In [1]: m = np.arange(1,26).reshape((5,5))

In [2]: m
Out[2]:
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])

and another array p = np.asarray([[1,1],[3,3]]). I wanted p to act as a array of indexes for m, i.e.:

m[p]
array([7, 19])

However I get:

In [4]: m[p]
Out[4]:
array([[[ 6,  7,  8,  9, 10],
        [ 6,  7,  8,  9, 10]],

       [[16, 17, 18, 19, 20],
        [16, 17, 18, 19, 20]]])

How can I get the desired slice of m using p?

like image 251
Jan Kuiken Avatar asked Apr 29 '26 04:04

Jan Kuiken


1 Answers

Numpy is using your array to index the first dimension only. As a general rule, indices for a multidimensional array should be in a tuple. This will get you a little closer to what you want:

>>> m[tuple(p)]
array([9, 9])

But now you are indexing the first dimension twice with 1, and the second twice with 3. To index the first dimension with a 1 and a 3, and then the second with a 1 and a 3 also, you could transpose your array:

>>> m[tuple(p.T)]
array([ 7, 19])
like image 140
Jaime Avatar answered May 02 '26 15:05

Jaime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!