0

Here's a numpy array:

>>> a = np.arange(30).reshape(5, 6)
>>> a
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]])

I can access a region of it using slices:

>>> a[1:3, 2:4]
array([[ 8,  9],
       [14, 15]])

I can replace either slice with a fancy index and get the same result:

>>> a[[1, 2], 2:4]
array([[ 8,  9],
       [14, 15]])
>>> a[1:3, [2, 3]]
array([[ 8,  9],
       [14, 15]])

If I replace both slices, I get a different result:

>>> a[[1, 2], [2, 3]]
array([ 8, 15])

What's going on here? Why don't all four of these produce the same result?

On a related note, is there a more pythonic way to grab multiple non-consecutive rows and columns than this?

>>> a[[1, 3]][:, [3, 5]]
array([[ 9, 11],
       [21, 23]])
Peter Drake
  • 443
  • 4
  • 17
  • The two lists (arrays) `broadcast` against each other. Look at what `np.ix_([1,2], [2,3])` produces. Or try to index with `[[1],[2]]`. – hpaulj Feb 17 '20 at 17:47
  • https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing - fancy indexing with lists – hpaulj Feb 17 '20 at 18:00

0 Answers0