Numpy: Index 3D array with index of last axis stored in 2D array

前端 未结 4 548
北海茫月
北海茫月 2020-12-19 00:18

I have a ndarray of shape(z,y,x) containing values. I am trying to index this array with another ndarray of shape(y,x) th

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 00:51

    Inspired by this thread, using np.ogrid:

    y,x = np.ogrid[0:3, 0:3]
    print [z_indices, y, x]
    [array([[1, 0, 2],
            [0, 0, 1],
            [2, 0, 1]]),
     array([[0],
            [1],
            [2]]),
     array([[0, 1, 2]])]
    
    print val_arr[z_indices, y, x]
    [[ 9  1 20]
     [ 3  4 14]
     [24  7 17]]
    

    I have to admit that multidimensional fancy indexing can be messy and confusing :)

提交回复
热议问题