Nump ndarray advanced indexing

I have ndarray 3 dimensions. How to choose index 0 and 1 from the first axis when choosing index 0 and 3 from the second axis and index 1 from the third axis?

I tried using the index [(0,1), (1, 3), 1], which gives a result completely different from what I thought it would produce.

So there are two questions here. What do [(0,1), (1, 3), 1] do? And how to create an index that solves my original question.

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

a[0, (1, 3), 1]  # produces array([3, 7])
a[(0,1), (1, 3), 1] # produces array([ 3, 17])

`` ``

0
source share
1 answer

When you indicate how you do it, NumPy does not interpret it as a choice of those indicators of each dimension. Instead, NumPy passes arguments to each other:

a[(0,1), (1, 3), 1] -> a[array([0, 1]), array([1, 3]), array([1, 1])]

, a[i, j, k][x] == a[i[x], j[x], k[x]].

, , , , (2, 2) shape (2,). , (2, 1), (1, 2) (2,), - . numpy.ix_ , . a[np.ix_([0, 1], [1, 3], [1])] , a[[0, 1], [1, 3], [1]], , a[[0, 1], [1, 3], 1], :

>>> a[np.ix_([0, 1], [1, 3], [1])]
array([[[ 3],
        [ 7]],

       [[13],
        [17]]])
>>> a[np.ix_([0, 1], [1, 3]) + (1,)]
array([[ 3,  7],
       [13, 17]])
>>> a[np.ix_([0, 1], [1, 3], [1])][:, :, 0]
array([[ 3,  7],
       [13, 17]])
+1

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


All Articles