Indexing with lists and arrays in numpy looks inconsistent

Inspired by this other question , I'm trying to ponder NumPy's advanced indexing and create a more intuitive understanding of how this works.

I found an interesting case. Here's the array:

>>> y = np.arange(10)
>>> y
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

if I index its scalar, I get a scalar, of course:

>>> y[4]
4

with a 1D array of integers, I get another 1D array:

>>> idx = [4, 3, 2, 1]
>>> y[idx]
array([4, 3, 2, 1])

so if I index it with a two-dimensional array of integers, I get ... what will I get?

>>> idx = [[4, 3], [2, 1]]
>>> y[idx]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

Oh no! Symmetry broken. I need to index a 3D array to get a 2D array!

>>> idx = [[[4, 3], [2, 1]]]
>>> y[idx]
array([[4, 3],
       [2, 1]])

What does numpy do this way?

, , numpy ( ) , , 2D 2D:

>>> idx = np.array([[4, 3], [2, 1]])
>>> y[idx]
array([[4, 3],
       [2, 1]])

, . ?

+6
1

numpy: , NumPy .

, arr[1, 2] arr[1][2], arr[[[4, 3], [2, 1]]] arr[[4, 3], [2, 1]] arr[4, 2] arr[3, 1].

, NumPy, , , " ": arr[[[[4, 3], [2, 1]]]].

:

. [0, 1, 2], , , [0, 1, 0]. :

>>> x = np.array([[1, 2], [3, 4], [5, 6]])
>>> x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])

:

, x[(1,2,3),] x[(1,2,3)]. x[1,2,3], , . , .

, , np.take:

>>> y.take([[4, 3], [2, 1]])  # 2D array
array([[4, 3],
       [2, 1]])

[ np.take] , "" ( ); , .

. , NumPy (array !) " ":

>>> y[np.asarray([[4, 3], [2, 1]])]
array([[4, 3],
       [2, 1]])
+2

All Articles