Assign value to numpy array with overlay index fragments

I want to assign a value to some segments of the array. I have segment indices as tuples (start_idx, end_idx). Segments can overlap or be sub-segments of each other.

a = np.zeros(12)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])
a[segments] = 1

Results:

a
>> array([1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0])

How can I mask all segments to get this output:

a
>> array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0])
+4
source share
4 answers

One option is to simply go through the segments and convert the ranges to the actual index:

a = np.zeros(10)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])

a[[i for s in segments for i in range(*s)]] = 1    
a
# array([ 1.,  1.,  1.,  0.,  0.,  0.,  1.,  1.,  1.,  1.])
+1
source

Here is one vector approach with borrowing ideas from this post-

def segment_arr(segments, L): # L being length of output array
    s = np.zeros(L,dtype=int)
    stop = segments[:,1]+1
    np.add.at(s,segments[:,0],1)
    np.add.at(s,stop[stop<len(s)],-1)
    return (s.cumsum()>0).astype(int)

Run Example -

In [298]: segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])

In [299]: segment_arr(segments, L=12)
Out[299]: array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0])
+2
source

:

a = np.zeros(10)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])
a[range(3)+range(1,2)+range(6,8)+range(8,10)] = 1
print (a)
+1

Just mention the trivial solution: use for-loop over segmentsand assign slices:

import numpy as np
a = np.zeros(12)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])

for seg in segments.tolist():  # the "tolist" is just an optimization here, you *could* omit it.
    a[seg[0]: seg[1]+1] = 1    # or just "seq[1]" if you want to exclude the end point
print(a)
# array([ 1.,  1.,  1.,  1.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.])
+1
source

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


All Articles