python - Group overlapping arrays -



python - Group overlapping arrays -

i have list of arrrays want set groups of overlapping values. instinct utilize itertools.groupby i'm not sure how create work.

some sample data:

a = np.array(range(10)) b = np.array(range(90,100)) c = np.array(range(50,60)) d = np.array(range(8,15)) e = np.array(range(55,80))

i want end 3 groups of overlapping (or non-contiguous) arrays:

groups = [[a,d],[b],[c,e]]

can utilize itertools.groupby this?

for k,g in itertools.groupby([a,b,c,d,e], lambda x: something?): groups.append(list(g))

but i'm not sure sort , grouping by. suggestions using or other method? thanks!

update:

thanks @abarnert solution below. you're right it's not huge number of arrays iterating brute forcefulness works fine. did clunky list comprehensions:

arrays, groups, idx = [a,b,c,d,e], [], [] n,x in enumerate(arrays): if n not in idx: group, idx = [x], idx+[n] n,x in enumerate(arrays): if n not in idx , any(np.where(np.logical_and(x<x[-1],x>x[0]))[0]): group.append(x), idx.append(n) groups.append(group)

if list of ranges little enough, can brute force: check each range against each other range overlap, "merging" them , starting loop on every time find one.

this bit clumsy write numpy arrays, let's utilize (python 3) range objects thought across:

def merge(x, y): homecoming range(min(x.start, y.start), max(x.stop, y.stop)) def overlap(x, y): homecoming x.start in y or y.start in x groups = {a: {a}, b: {b}, c: {c}, d: {d}, e: {e}} while true: key, value in groups.items(): otherkey, othervalue in groups.items(): if key otherkey: go on if overlap(key, otherkey): del groups[otherkey] del groups[key] groups[merge(key, otherkey)] = value | othervalue break else: go on break else: break

this wasteful algorithm, considering have few plenty objects assign them each variable, cares? should dead easy understand, , that's more of import here.

python numpy itertools

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -