嵌套循环执行多多边形相交测试仅返回单个MultiLinestring求助
问题分析与修正
你的代码存在几个关键错误,导致最终只得到单个交集结果,逐一修正如下:
- 错误的循环对象调用:
for a in shape_geo()中的shape_geo()是错误写法,shape_geo是GeoSeries对象而非函数,直接使用shape_geo即可。 - 错误的相等判断处理:
exit仅为函数名未执行,且用exit会直接终止程序,应改用continue跳过当前循环,避免多边形与自身计算交集。 - 列表元素添加错误:
intborders = b.intersection(a)是直接覆盖列表变量,而非向列表添加元素,需改为intborders.append(b.intersection(a))来保留所有交集结果。 - 冗余且错误的变量定义:
shape_borders = shapes_geo.iloc[range(len(world_geo))]中world_geo未定义,且该行代码无实际作用,可直接删除。
修正后的代码:
from geopandas import read_file, GeoSeries from matplotlib.pyplot import subplots, savefig, title from pyproj import Geod shapes = read_file("../data/ne_10m_admin_0.shp") shapes_geo = shapes.geometry bordersb = shapes_geo intborders = [] for b in bordersb: for a in shapes_geo: if b.equals(a): continue # 跳过自身,不计算交集 elif b.touches(a): intersection = b.intersection(a) intborders.append(intersection) # 可选:将列表转为GeoSeries,方便后续可视化或分析 intborders_geo = GeoSeries(intborders) print(intborders_geo)
运行后,intborders列表会包含所有相邻多边形的交集结果(均为MultiLinestring),转为GeoSeries后也能更便捷地进行后续操作。
内容的提问来源于stack exchange,提问作者wodseaur
相关产品推荐
相关产品推荐

