0

Given a GeoDataFrame where the geometry column contains both Polygons and MultiPolygons.

How can I force the orientation (left-hand-rule or right-hand-rule) on these geometries?

0

The orient functionality is included within shapely as function in the ops module from version 1.7a2 and onwards.

If you have this function you can do the following:

from shapely.ops import orient # version >=1.7a2
gdf.geometry = gdf.geometry.apply(orient, args=(-1,))

If you have an earlier version of shapely and cannot update to the latest version, try to emulate this new functionality with the following function:

from shapely.geometry.base import BaseMultipartGeometry
from shapely.geometry.polygon import orient as orient_
from shapely.geometry import Polygon

def orient(geom, sign=1.0):
    if isinstance(geom, BaseMultipartGeometry):
        return geom.__class__(
            list(
                map(
                    lambda geom: orient(geom, sign),
                    geom.geoms,
                )
            )
        )
    if isinstance(geom, (Polygon,)):
        return orient_(geom, sign)
    return geom

gdf.geometry = gdf.geometry.apply(orient, args=(-1,))
  • the geom.__class__ bit is clever! I like it. A bit of note on dataframe best practices: while assigning dataframe columns with the dot-accessor works, it's not a good habit to have as you could overwrite the dataframe's methods or properties (for instance if you had a column called "max"). Best practice would be to use the .assign method (gdf = gdf.assign(geometry=gdf.loc[:, 'geometry'].apply(orient, args=(1,)))). Certainly more verbose, but safer and easier to incorporate into a longer chain of commands – Paul H Sep 20 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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