Indexing multidimensional arrays using 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 act as an array of indices 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 to get the desired m fragment using p ?

+2
source share
1 answer

Numpy uses your array to index only the first dimension. As a rule, indexes for a multidimensional array should be in a tuple. This will bring you closer to what you want:

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

But now you index the first dimension twice with 1, and the second with 3. To index the first dimension with 1 and 3, and then the second with 1 and 3 as well, you can move your array:

 >>> m[tuple(pT)] array([ 7, 19]) 
+3
source

Source: https://habr.com/ru/post/1488437/


All Articles