Created
September 2, 2020 20:15
-
-
Save JoaoCarabetta/7739a88e3c7f577929d4c353dc96d2ad to your computer and use it in GitHub Desktop.
Line and Polygon Intersection for Geopandas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def line_polygon_intersection(line_df, poly_df): | |
""" | |
It cuts the line if it sits between polygons. | |
""" | |
column_geom_poly = poly_df._geometry_column_name | |
column_geom_line = line_df._geometry_column_name | |
spatial_index = line_df.sindex | |
bbox = poly_df.geometry.apply(lambda x: x.bounds) | |
sidx = bbox.apply(lambda x: list(spatial_index.intersection(x))) | |
nei = [] | |
for i, j in enumerate(sidx): | |
for k in j: | |
nei.append([i, k]) | |
if nei != []: | |
pairs = pd.DataFrame(nei, columns=["__idx1", "__idx2"]) | |
left = poly_df.geometry.take(pairs["__idx1"].values) | |
left.reset_index(drop=True, inplace=True) | |
right = line_df.geometry.take(pairs["__idx2"].values) | |
right.reset_index(drop=True, inplace=True) | |
intersections = pd.concat([left, right], 1) | |
intersections = intersections.apply(lambda x: x[column_geom_line].intersection(x[column_geom_poly]), 1) | |
intersections = gpd.GeoDataFrame(intersections, columns=['geometry']) | |
pairs_intersect = pairs[~intersections.is_empty] | |
geom_intersect = intersections[~intersections.is_empty].geometry | |
# merge data for intersecting geometries | |
line_df = line_df.reset_index(drop=True) | |
poly_df = poly_df.reset_index(drop=True) | |
dfinter = pairs_intersect.merge( | |
poly_df.drop(poly_df._geometry_column_name, axis=1), | |
left_on="__idx1", | |
right_index=True, | |
) | |
dfinter = dfinter.merge( | |
line_df, | |
left_on="__idx2", | |
right_index=True, | |
suffixes=["_1", "_2"], | |
) | |
result = gpd.GeoDataFrame(dfinter, geometry=geom_intersect, crs=poly_df.crs) | |
result.reset_index(drop=True, inplace=True) | |
result.drop(["__idx1", "__idx2"], axis=1, inplace=True) | |
return result | |
else: | |
return pd.DataFrame() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment