Numpy slice of arbitrary dimensions

前端 未结 3 1916
南方客
南方客 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:17

    Actually, just found the answer. As stated in numpy's documentation this can be done with the slice object. In my particular case, this would do it:

    idx = [slice(None)] * (myarray.ndim - 1) + [i] 
    my_slice = myarray[idx]
    

    The slice(None) is equivalent to choosing all elements in that index, and the last [i] selects a specific index for the last dimension.

提交回复
热议问题