I have one list of data as follows:
from shapely.geometry import box
data = [box(1,2,3,4), box(5,6,7,8), box(1,2,3,4)]
codes = ['A','B','C']
The list 'data' has following elements:
A = box(1,2,3,4)
B = box(5,6,7,8)
C = box(1,2,3,4)
I have to check if an element intersect with any other elements. If intersects, they should put in one tuple; and if not intersect they should put in different tuple. The expected result is:
result = [(A,C), (B)]
How to do it?
I tried it as:
results = []
for p,c in zip(data,codes):
for x in data:
if p.intersects(x): ##.intersects return true if they overlap else false
results.append(c)
print results
A LineString has zero area and non-zero length. >>> from shapely.geometry import LineString >>> line = LineString([(0, 0), (1, 1)]) >>> line. area 0.0 >>> line. length 1.4142135623730951. Its x-y bounding box is a (minx, miny, maxx, maxy) tuple.
unary_union. Returns a geometry containing the union of all geometries in the GeoSeries .
Shapely is a BSD-licensed Python package for manipulation and analysis of planar geometric objects. It is using the widely deployed open-source geometry library GEOS (the engine of PostGIS, and a port of JTS).
Keep a dict of objects mapped to A,B and C, a set of matched objects and only add the single elements that have no matches after we get to a new letter if they are not in our matched set as all possible combinations will have been tested:
from shapely.geometry import box
from itertools import combinations
codes = ["A", "B", "C"]
d = dict(zip(codes, data))
prev = codes[0]
matched, out = set(), []
for p1, p2 in combinations(codes, 2):
if d[p1].intersects(d[p2]):
out.append((p1, p2))
matched.update([p1, p2])
# when p1 is a new letter, we have tried all combs for that prev
# if prev is not in matched it did not intersect any other so
# add it as a single tuple and add to matched to avoid dupes
elif p1 != prev and prev not in matched:
out.append(tuple(prev,))
matched.add(prev)
prev = p1
# catch the last letter
if p2 not in matched:
out.append(tuple(p2,))
print(out)
[('A', 'C'), ('B',)]
from shapely.geometry import box
data = [box(1,2,3,4), box(5,6,7,8), box(1,2,3,4)]
codes = ['A','B','C']
Create a dictionary to map your code to your boxes:
d = dict(zip(codes, data))
Check all combinations:
intersecting = set()
for i, a in enumerate(codes, 1):
for b in codes[i:]:
if d[a].intersection(d[b]):
intersecting |= {a, b}
print(tuple(intersecting), tuple(set(codes)^intersecting))
# ('C', 'A') ('B',)
Tuples will be unordered because sets were used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With