Numpy slice of arbitrary dimensions

前端 未结 3 1914
南方客
南方客 2020-12-08 03:35

I would like to slice a numpy array to obtain the i-th index in the last dimension. For a 3D array, this would be:

slice = myarray[:,:,i]

B

3条回答
  •  北海茫月
    2020-12-08 04:35

    In terms of slicing an arbitrary dimension, the previous excellent answers can be extended to:

    indx = [slice(None)]*myarray.ndim
    indx[slice_dim] = i
    sliced = myarray[indx]
    

    This returns the slice from any dimension slice_dim - slice_dim = -1 reproduces the previous answers. For completeness - the first two lines of the above listing can be condensed to:

    indx = [slice(None)]*(slice_dim) + [i] + [slice(None)]*(myarray.ndim-slice_dim-1)
    

    though I find the previous version more readable.

提交回复
热议问题