alex_bn_lee

导航

[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)

 

posted on 2025-02-14 13:46  McDelfino  阅读(20)  评论(0)    收藏  举报