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

前端 未结 4 561
北海茫月
北海茫月 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 01:00

    You can use choose to make the selection:

    >>> z_indices.choose(val_arr)
    array([[ 9,  1, 20],
           [ 3,  4, 14],
           [24,  7, 17]])
    

    The function choose is incredibly useful, but can be somewhat tricky to make sense of. Essentially, given an array (val_arr) we can make a series of choices (z_indices) from each n-dimensional slice along the first axis.

    Also: any fancy indexing operation will create a new array rather than a view of the original data. It is not possible to index val_arr with z_indices without creating a brand new array.

提交回复
热议问题