1

I am trying to densify geometry of polygons loaded by GeoPandas using ogr.Geometry Segmentize. When I print new geometry, it is densified as intended, but it will never save into the shapefile. It should just overwrite the old one, but geometry remains the same as the original one. I have no idea what is wrong. It is not giving me an error.

The code looks like this:

import geopandas as gpd
from osgeo import ogr
from shapely.wkt import loads

path = "/Users/martin/Tess/b3.shp"
objects = gpd.read_file(path)  # load file into geopandas

for index, row in objects.iterrows():
    wkt = row['geometry'].wkt  # shapely Polygon to wkt
    geom = ogr.CreateGeometryFromWkt(wkt)  # create ogr geometry
    geom.Segmentize(2)  # densify geometry
    wkt2 = geom.ExportToWkt()  # ogr geometry to wkt
    new = loads(wkt2)  # wkt to shapely Polygon
    row['geometry'] = new  # overwrite old geomtry with densified one

objects.to_file("/Users/martin/Tess/b3s.shp")

Any idea what is wrong?

1 Answer 1

3

You cannot modify the row you are iterating over directly, you either have to make a new column or to modify the original dataframe. For example:

for index, row in objects.iterrows():
    wkt = row['geometry'].wkt
    ...
    new = loads(wkt2)
    objects.loc[index, 'geometry'] = new

Or an alternative (in my opinion cleaner way, but that is subjective), is to write a function for it and apply that to the geometries:

def segmentize(geom):
    wkt = geom.wkt  # shapely Polygon to wkt
    geom = ogr.CreateGeometryFromWkt(wkt)  # create ogr geometry
    geom.Segmentize(2)  # densify geometry
    wkt2 = geom.ExportToWkt()  # ogr geometry to wkt
    new = loads(wkt2)  # wkt to shapely Polygon
    return new

objects['geometry'] = objects['geometry'].map(segmentize)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.