1

Looking at the answers to this question: How to understand numpy's combined slicing and indexing example

I'm still unable to understand the result of indexing with a combination of a slice and two 1d arrays, like this:

>>> m = np.arange(36).reshape(3,3,4)
>>> m
array([[[ 0,  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, 26, 27],
        [28, 29, 30, 31],
        [32, 33, 34, 35]]])

>>> m[1:3, [2,1],[2,1]]
array([[22, 17],
       [34, 29]])

Why is the result equivalent to this?

np.array([
         [m[1,2,2],m[1,1,1]],
         [m[2,2,2],m[2,1,1]]
         ])
shenun
  • 85
  • 5
  • I think your example won't work since with `m[1:3, [2,3],[2,3]]` the array is sized `(3,3,4)` so the second axis indices only go up to `2` (but your indexing tries for `3`). Could you please check your example and edit the question if necessary? – tom10 Oct 11 '20 at 15:19
  • Do you understand how `m[0,[2,2],[1,1]]` works? or `m[0,2,2]`. Figure out what the initial slice is doing, and then focus on the behavior the remaining indices on one of those 'planes'. – hpaulj Oct 11 '20 at 15:47
  • @tom10: my bad. It should've been m[1:3, [2,1],[2,1]] – shenun Oct 11 '20 at 16:47
  • @hpaulj: I understand m[0,[2,1]] - which gives a (2,4) array (by taking 2nd and 1st row of m[0]). It's the next addition of [2,1] that's tripping me off. How is m[0,[2,1],[2,1]] selecting a len_2 vector from (2,4) array of m[0,[2,1]]? – shenun Oct 11 '20 at 16:57
  • 1
    Those `[x,y],[z,w]` lists/arrays work together to select a "diagonal", e.g `(x,z)` and `(y,w)` elements. More generally indexing arrays `broadcast` together, allowing us to select blocks. But here it's a 1d block. It's logical, but you may have to experiment to get a more intuitive feel. – hpaulj Oct 11 '20 at 17:13
  • I see. Thanks. That's helpful. – shenun Oct 11 '20 at 17:16

0 Answers0