使用 GeoPandas 获取相交线串时出现问题

问题描述 投票:0回答:1

我在使用 GeoPandas 从与多边形的交点获取线串时遇到问题。线串是自相交的,这就是导致我出现问题的原因。

与多边形相交的线:

enter image description here

给出以下代码:

import geopandas as gp
from shapely.geometry import LineString, Polygon

# Draw a polygon that is 100 x 100 units, starting at coordinates 0, 0
polygon = Polygon([(50, 0), (50, 100), (100, 100), (100, 0)])

# Convert the polygon to a geodataframe
polygon = gp.GeoDataFrame(index=[0], crs='EPSG:4326', geometry=[polygon])

# Draw a horizontal line that starts at coordinates 50, 0 and is 200 units long
line = LineString([(0, 50), (75, 50), (70, 35), (55, 40), (250, 50)])

# Convert the line to a geodataframe
line = gp.GeoDataFrame(index=[0], crs='EPSG:4326', geometry=[line])

print(line)

# Intersect the line with the polygon
intersection = line.intersection(polygon)

print(intersection)

我有以下结果:

0 线串 (0.00000 50.00000, 75.00000 50.0000... 0 多线字符串 ((50.00000 50.00000, 75.00000 ...

相交后,我返回一个多线串而不是线串。 该线被多边形分割(期望),但也被分割成多条自相交的线(不期望)。

我尝试使用一元联合重新加入多行,但没有成功。 输出仍然是多行字符串。

我不确定我还能做什么来仅将多边形内包含的线部分保留为单线。 关于我如何能够实现这一目标有什么想法吗?

python geopandas intersection shapely
1个回答
0
投票

因为 line_merge 在自相交时不会重建单个线串,所以我看到的唯一选择是提取坐标并创建一个新的线串,这会产生单个线串。

在代码示例中,我使用了一些仅在 shapely 2 中可用的功能,因此它需要相对最新的 shapely 版本。

代码示例:

import geopandas as gp
import shapely
from shapely.geometry import LineString, Polygon

# Draw a polygon that is 100 x 100 units, starting at coordinates 0, 0
polygon = Polygon([(50, 0), (50, 100), (100, 100), (100, 0)])

# Convert the polygon to a geodataframe
polygon = gp.GeoDataFrame(index=[0], crs='EPSG:4326', geometry=[polygon])

# Draw a horizontal line that starts at coordinates 50, 0 and is 200 units long
line = LineString([(0, 50), (75, 50), (70, 35), (55, 40), (250, 50)])

# Convert the line to a geodataframe
line = gp.GeoDataFrame(index=[0], crs='EPSG:4326', geometry=[line])

# print(line)

# Intersect the line with the polygon
intersection = line.intersection(polygon)

print(f"{intersection=}")

# Recreate the intersection line from its coordinates
intersection_line = shapely.linestrings(shapely.get_coordinates(intersection))

print(f"{intersection_line=}")
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.