Ayla
Ayla

Reputation: 41

Get intersections of all linestrings within a GeoDataFrame (geopandas) in python

I have a GeoDataFrame containing some streets of a city (every row is a linestring). I would like to obtain another GeoDataFrame with all the intersections between those streets (as Points). All I can see is how to intersect 2 different GeoDataFrames. Is there any way to do it other than looping over the streets and intersecting with the rest? Thanks!

Upvotes: 4

Views: 1302

Answers (1)

Bera
Bera

Reputation: 1949

Dissolve the lines into one multiline. This will create new coordinates at all intersections. Find them by comparing the coordinates of the original df and the dissolved df.

import geopandas as gpd
import numpy as np
from shapely.geometry import LineString

#Create a line geodataframe with 100 random lines
n=100
x1_coords = np.random.random(n)
x2_coords = np.random.random(n)
y1_coords = np.random.random(n)
y2_coords = np.random.random(n)
lines = [LineString([(x1, y1), (x2, y2)]) 
         for x1,y1,x2,y2 in zip(x1_coords, y1_coords, x2_coords, y2_coords)]

line_df = gpd.GeoDataFrame(geometry=lines)

#Create a dataframe of all line x and y coordinates
coords_pre_dissolve = line_df.get_coordinates()

#Dissolve the line df into a one row multiline .
#  This will insert new vertices at all line intersections.
#  Extract them into a dataframe
coords_post_dissolve = line_df.dissolve().get_coordinates()

#Find new coordinates that are present in the multiline df but not in the original line df
intersections = coords_post_dissolve.merge(coords_pre_dissolve, 
                           on=["x","y"], how="left", indicator=True).query("_merge=='left_only'").drop_duplicates()

#Create a point geodataframe of the new coordinates
intersections = gpd.GeoDataFrame(geometry=gpd.points_from_xy(x=intersections.x, y=intersections.y))

ax = line_df.plot(figsize=(15,15), zorder=1, linewidth=1, color="gray")
intersections.plot(ax=ax, zorder=2, color="red")

enter image description here

Upvotes: 0

Related Questions