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
I think one way would be to use slice(None)
:
>>> m = np.arange(2*3*5).reshape((2,3,5))
>>> axis, start, end = 2, 1, 3
>>> target = m[:, :, 1:3]
>>> target
array([[[ 1, 2],
[ 6, 7],
[11, 12]],
[[16, 17],
[21, 22],
[26, 27]]])
>>> slc = [slice(None)] * len(m.shape)
>>> slc[axis] = slice(start, end)
>>> np.allclose(m[slc], target)
True
I have a vague feeling I've used a function for this before, but I can't seem to find it now..