Construct Numpy index given list of start and end positions

I have two numpy.array objects with the same size (one-dimensional), one of which contains a list of index start positions and the other contains a list of index end positions (alternatively, I can say that I have a list of initial positions and window lengths). In case it matters, the sectors formed by the start and end positions ensure that they do not overlap. I'm trying to figure out how to use these start and end positions to form an index for another array object, without having to use a loop.

For instance:

import numpy as np
start = np.array([1,7,20])
end = np.array([3,10,25])

Want a link

somearray[1,2,7,8,9,20,21,22,23,24])
+3
source share
4 answers

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 the 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

NumPy (lens) , .

+3

Numpy arange , . ?

In [11]: idx = np.hstack([np.arange(s,e) for s,e in  zip(start, end)])

In [12]: idx
Out[12]: array([ 1,  2,  7,  8,  9, 20, 21, 22, 23, 24])

somearray[idx].

+2

:

>>> import numpy as np
>>> start = np.array([1,7,20])
>>> end = np.array([3,10,25])
>>> na=np.fromiter(sum([range(s,e) for s,e in zip(start,end)],[]),np.int)
>>> na
array([ 1,  2,  7,  8,  9, 20, 21, 22, 23, 24])

, 1) ; 2) , numpy.

0

: " , ", .

If it startindicates the beginning, and endis the length, you can get your elements this way:

>>> [i for iter in [range(s,s+e) for s,e in zip(start,end)] for i in iter]
[1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25, 26, 
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]

If you want to match your array of examples, and endis really the -1 element, you can get your elements this way:

>>> [i for iter in [range(*t) for t in zip(start,end)] for i in iter]
[1, 2, 7, 8, 9, 20, 21, 22, 23, 24]
>>> somearray=np.array(_)
>>> somearray
array([1, 2, 7, 8, 9, 20, 21, 22, 23, 24])

Alternative:

>>> sum([range(*t) for t in zip(start,end)],[])
[1, 2, 7, 8, 9, 20, 21, 22, 23, 24]

Remember that you simply generate a list of integers described in your tuples as an index to your numpy array. Any of them can use xrangevs rangeif it's faster / better in your case.

-1
source

Source: https://habr.com/ru/post/1785785/


All Articles