I have a 3D numpy array x
. I want to take a subset of each slice on axis 0 (each subset is the same shape, but with start and end indices that may be different for each slice) and compose these into a separate 3D numpy array. I can achieve this with
import numpy as np
x = np.arange(24).reshape((3, 4, 2))
starts = [0, 2, 1]
ends = [2, 4, 3]
np.stack([x[i, starts[i]:ends[i]] for i in range(3)])
but 1) is there any way to do this in a single operation using fancy indexing, and 2) will doing so speed things up?