Python: Combine array rows based on difference between prior row's last element and posterior row's first element -
as title, given (n, 2) numpy array recording series of segment's start , end indices, example n=6:
import numpy np # x records (start, end) index pairs corresponding 6 segments x = np.array(([0,4], # 1st seg ranges index 0 ~ 4 [5,9], # 2nd seg ranges index 5 ~ 9, etc. [10,13], [15,20], [23,30], [31,40]))
now want combine segments small interval between them. example, merge consecutive segments if interval no larger 1, desired output be:
y = np.array([0,13], # cuz 1st seg's end close 2nd's start, # , 2nd seg's end close 3rd's start, combined. [15,20], # 4th seg away prior , posterior segs, # remains untouched. [23,40]) # 5th , 6th segs close, combined
so output segments turn out 3 instead of six. suggestion appreciated!
if we're able assume segments ordered , none wholly contained within neighbor, identifying gap between end value in 1 range , start of next exceeds criteria:
start = x[1:, 0] # select columns, ignoring beginning of first range end = x[:-1, 1] # , end of final range mask = start>end+1 # identify consecutive rows have great gap
then stitching these pieces together:
np.array([np.insert(start[mask], 0, x[0, 0]), np.append(end[mask], x[-1, -1])]).t out[96]: array([[ 0, 13], [15, 20], [23, 40]])
wiki
Comments
Post a Comment