Slicing a numpy array along a dynamically specified axis

前端 未结 5 1745
不思量自难忘°
不思量自难忘° 2020-11-29 10:54

I would like to dynamically slice a numpy array along a specific axis. Given this:

axis = 2
start = 5
end = 10

I want to achieve the same r

5条回答
  •  眼角桃花
    2020-11-29 11:19

    There is an elegant way to access an arbitrary axis n of array x: Use numpy.moveaxis¹ to move the axis of interest to the front.

    x_move = np.moveaxis(x, n, 0)  # move n-th axis to front
    x_move[start:end]              # access n-th axis
    

    The catch is that you likely have to apply moveaxis on other arrays you use with the output of x_move[start:end] to keep axis order consistent. The array x_move is only a view, so every change you make to its front axis corresponds to a change of x in the n-th axis (i.e. you can read/write to x_move).


    1) You could also use swapaxes to not worry about the order of n and 0, contrary to moveaxis(x, n, 0). I prefer moveaxis over swapaxes because it only alters the order concerning n.

提交回复
热议问题