Numpy fancy indexing in multiple dimensions

后端 未结 1 602
深忆病人
深忆病人 2021-01-13 07:57

Let\'s say I have an numpy array A of size n x m x k and another array B of size n x m that has indices from 1 to k. I want to access each n x m slice of A using the index g

1条回答
  •  生来不讨喜
    2021-01-13 08:18

    Suppose

    import numpy as np
    np.random.seed(0)
    
    n,m,k = 2,3,5
    A = np.arange(n*m*k,0,-1).reshape((n,m,k))
    print(A)
    # [[[30 29 28 27 26]
    #   [25 24 23 22 21]
    #   [20 19 18 17 16]]
    
    #  [[15 14 13 12 11]
    #   [10  9  8  7  6]
    #   [ 5  4  3  2  1]]]
    
    B = np.random.randint(k, size=(n,m))
    print(B)
    # [[4 0 3]
    #  [3 3 1]]
    

    To create this array,

    print(A.reshape(-1, k)[np.arange(n * m), B.ravel()])
    # [26 25 17 12  7  4]
    

    as a nxm array using fancy indexing:

    i,j = np.ogrid[0:n, 0:m]
    print(A[i, j, B])
    # [[26 25 17]
    #  [12  7  4]]
    

    0 讨论(0)
提交回复
热议问题