[SOLVED] Inconsistent advanced indexing in NumPy

Issue

Why are the following indexing forms produce differently shaped outputs?

a = np.zeros((5, 5, 5, 5))
print(a[:, :, [1, 2], [3, 4]].shape)
# (5, 5, 2)

print(a[:, :, 1:3, [3, 4]].shape)
#(5, 5, 2, 2)

Almost certain I’m missing something obvious.

Solution

The first one,

a[:, :, [1, 2], [3, 4]]

takes indices pairwise and selects the following subarrays:

a[:, :, 1, 3]
a[:, :, 2, 4]

whereas the second one generates all possible combos (and shapes it accordingly), i.e.

a[:, :, 1, 3]
a[:, :, 1, 4]
a[:, :, 2, 3]
a[:, :, 2, 4]

This can be verified by running the following exercise. Rather than initializing a as a zero array, use np.arange and reshape it

a = np.arange(5**4).reshape((5, 5, 5, 5))
print(a[:, :, [1, 2], [3, 4]])

The first few lines of the output are

[[[  8  14]
  [ 33  39]
  [ 58  64]...

and the array a itself is

[[[[  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]]...

So 8 comes at (1,3) (In the innermost 2D array, 1: 2nd row, 3:4th column) as expected and 14 comes at (2, 4). Similarly, 33 is also at index (1,3) and 39 at (2,4) in the next 2D subarray.

Answered By – R. S. Nikhil Krishna

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *