在Geopandas/Python中实现ArcGIS Feature-to-Polygon:拆分重叠多边形
需求说明
我有一个包含重叠多边形(缓冲区)的GeoDataFrame,想要将重叠区域拆分为唯一的无重叠多边形,同时保留非重叠部分,最终输出完全无重叠的多边形集合,实现ArcMap/ArcGIS Desktop中Feature-to-Polygon工具的效果。
示例代码(修正版)
原示例代码缺少id列,修正后如下:
import geopandas as gpd from shapely.geometry import Point import matplotlib.pyplot as plt import numpy as np # 创建带id字段的GeoDataFrame polys = gpd.GeoDataFrame( data={'id': [1, 2, 3, 4]}, geometry=[Point(0, 0), Point(1, 1), Point(1, 2), Point(2, 1)] ) # 生成半径为1的缓冲区多边形 polys['geometry'] = polys.buffer(1) # 绘制当前重叠效果 ax2 = polys.plot(figsize=(5,5), edgecolor='white', color='gray') for name in polys['id']: polys.loc[polys['id'] == name].plot(edgecolor='white', color=np.random.rand(3,), ax=ax2) ax2.axis('scaled') plt.title('当前重叠效果') plt.show()
当前输出效果

期望输出效果

解决方案
通过geopandas结合shapely的核心方法可实现需求,步骤如下:
- 对所有多边形求并集,得到包含所有区域边界的几何对象
- 提取并集的边界线,将其多边形化,得到所有无重叠的子多边形
- 将结果转为GeoDataFrame
完整实现代码:
import geopandas as gpd from shapely.geometry import Point, MultiLineString from shapely.ops import polygonize import matplotlib.pyplot as plt import numpy as np # 1. 构建原始数据 polys = gpd.GeoDataFrame( data={'id': [1, 2, 3, 4]}, geometry=[Point(0, 0), Point(1, 1), Point(1, 2), Point(2, 1)] ) polys['geometry'] = polys.buffer(1) # 2. 计算所有多边形的并集,提取边界线 union_geom = polys.unary_union # 处理并集为MultiPolygon的情况,提取每个子多边形的边界 if hasattr(union_geom, 'geoms'): boundary_lines = MultiLineString([poly.boundary for poly in union_geom.geoms]) else: boundary_lines = union_geom.boundary # 3. 将边界线多边形化,生成无重叠的多边形 non_overlap_polys = list(polygonize(boundary_lines)) # 4. 转为GeoDataFrame,保留原坐标系 result_gdf = gpd.GeoDataFrame(geometry=non_overlap_polys, crs=polys.crs) # 5. 绘制结果 ax = result_gdf.plot(figsize=(5,5), edgecolor='white', cmap='tab10') ax.axis('scaled') plt.title('无重叠多边形结果') plt.show()
补充说明
- 上述代码生成的无重叠多边形与ArcGIS Feature-to-Polygon工具的输出效果一致
- 若需要将原始多边形的属性(如
id)关联到新生成的多边形,可使用geopandas.sjoin进行空间连接,匹配每个新多边形对应的原始属性
内容的提问来源于stack exchange,提问作者user2503169
相关产品推荐
相关产品推荐

