I have two identically-sized numpy.array objects (both one-dimensional), one of which contains a list of starting index positions, and the other of which contains a list of ending index positions (alternatively you could say I have a list of starting positions and window lengths). In case it matters, the slices formed by the starting and ending positions are guaranteed to be non-overlapping. I am trying to figure out how to use these starting and ending positions to form an index for another array object, without having to use a loop.
For example:
import numpy as np
start = np.array([1,7,20])
end = np.array([3,10,25])
Want to reference
somearray[1,2,7,8,9,20,21,22,23,24])
I would use
np.r_[tuple(slice(s, e) for s, e in zip(start, end))]
EDIT: Here is a solution that does not use a Python loop:
def indices(start, end):
lens = end - start
np.cumsum(lens, out=lens)
i = np.ones(lens[-1], dtype=int)
i[0] = start[0]
i[lens[:-1]] += start[1:]
i[lens[:-1]] -= end[:-1]
np.cumsum(i, out=i)
return i
This only creates a single temporary NumPy array (lens
) and is much faster than any of the other solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With