I have a 1D numpy array, and some offset/length values. I would like to extract from this array all entries which fall within offset, offset+length, which are then used to build up a new ‘reduced’ array from the original one, that only consists of those values picked by the offset/length pairs.
For a single offset/length pair this is trivial with standard array slicing [offset:offset+length]. But how can I do this efficiently (i.e. without any loops) for many offset/length values?
Thanks,
Mark
There is the naive method; just doing the slices:
The following might be faster, but you would have to test/benchmark.
It works by constructing a list of the desired indices, which is valid method of indexing a numpy array.
It’s not clear if this would actually be faster than the naive method but it might be if you have a lot of very short intervals. But I don’t know.
(This last method is basically the same as @fraxel’s solution, just using a different method of making the index list.)
Performance testing
I’ve tested a few different cases: a few short intervals, a few long intervals, lots of short intervals. I used the following script:
This outputs:
This suggests that my first method is the fastest when you have a few intervals (and it is significantly faster), and my second is the fastest when you have lots of intervals.