find intersections between range tuples with numpy

Viewed 258

I have a list of ranges like this:

[
(1,3),
(13,13),
(14,16),
(15,19),
]

In which I need to find intersecting ranges. In this case it would be the third and fourth line. What is an efficient way to do this in numpy?

2 Answers

This returns a column that tells you if a row is overlapping with its next interval:

a = np.array([(1,3),(13,13),(14,16),(15,19)])
a.sort()
intervals = pd.DataFrame(a,columns=['start','end'])
print((intervals.end-intervals.start.shift(-1))>0)

output:

0    False
1    False
2     True
3    False

Find the index of overlapping intervals:

idx = np.array(np.where((intervals.end-intervals.start.shift(-1))>0))
print(np.hstack((idx,idx+1)))
#[[2 3]]

You can do similar with numpy. You have to either write the shift function or use scipy to shift or use numpy.roll.

This can also be done without a module, you can use the set.intersection() method:

l = [(1,3),
     (13,13),
     (14,16),
     (15,19)]

print([(l[i-1],t) for i,t in enumerate(l) if set(range(t[0],t[1])).intersection(range(l[i-1][0],l[i-1][1]))])

Output:

[((14, 16), (15, 19))]
Related