[1097] Converting 3D geometries to 2D geometries in a GeoDataFrame
MultiPolygon
import geopandas as gpd from shapely.geometry import MultiPolygon, Polygon # Sample GeoDataFrame with 3D multipolygons data = {'geometry': [ MultiPolygon([ Polygon([(0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), (0, 0, 1)]), Polygon([(2, 2, 2), (3, 2, 2), (3, 3, 2), (2, 3, 2), (2, 2, 2)]) ]), MultiPolygon([ Polygon([(4, 4, 3), (5, 4, 3), (5, 5, 3), (4, 5, 3), (4, 4, 3)]), Polygon([(6, 6, 4), (7, 6, 4), (7, 7, 4), (6, 7, 4), (6, 6, 4)]) ]) ]} gdf = gpd.GeoDataFrame(data, crs="EPSG:4326") for i in range(len(gdf)): print(gdf.geometry[i])
Output:
MULTIPOLYGON Z (((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)), ((2 2 2, 3 2 2, 3 3 2, 2 3 2, 2 2 2))) MULTIPOLYGON Z (((4 4 3, 5 4 3, 5 5 3, 4 5 3, 4 4 3)), ((6 6 4, 7 6 4, 7 7 4, 6 7 4, 6 6 4)))
Next, define the function:
# Function to convert 3D polygons to 2D polygons def convert_3d_to_2d(multipolygon): polygons_2d = [] for polygon in list(multipolygon.geoms): polygons_2d.append(Polygon([(x, y) for x, y, z in polygon.exterior.coords])) return MultiPolygon(polygons_2d) # Convert 3D multipolygons to 2D multipolygons gdf['geometry'] = gdf['geometry'].apply(convert_3d_to_2d) for i in range(len(gdf)): print(gdf.geometry[i])
Output:
MULTIPOLYGON Z (((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)), ((2 2 2, 3 2 2, 3 3 2, 2 3 2, 2 2 2))) MULTIPOLYGON Z (((4 4 3, 5 4 3, 5 5 3, 4 5 3, 4 4 3)), ((6 6 4, 7 6 4, 7 7 4, 6 7 4, 6 6 4))) MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((2 2, 3 2, 3 3, 2 3, 2 2))) MULTIPOLYGON (((4 4, 5 4, 5 5, 4 5, 4 4)), ((6 6, 7 6, 7 7, 6 7, 6 6)))
Combined script:
from shapely.geometry import MultiPolygon, Polygon # Function to convert 3D polygons to 2D polygons def convert_3d_to_2d(multipolygon): polygons_2d = [] for polygon in list(multipolygon.geoms): polygons_2d.append(Polygon([(x, y) for x, y, z in polygon.exterior.coords])) return MultiPolygon(polygons_2d) # Convert 3D multipolygons to 2D multipolygons gdf['geometry'] = gdf['geometry'].apply(convert_3d_to_2d)
分类:
Python Study
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)