I have a GeoDataframe containing multi-polygon geography. If I use the centroid
function to find the centers, the results are not always located inside any of the polygons e.g. for a series of islands. So, how do I find the centroid of only the first polygon in the multi-polygon shape?
For the centroid of the first polygon of a MultiPolygon you can just do
mp[0].centroid
There are several ways to apply that, e.g. first limit each MultiPolygon in your dataframe to the first Polygon.
def keep_first(geo):
if geo.geom_type == 'Polygon':
return geo
elif geo.geom_type == 'MultiPolygon':
return geo[0]
df.geometry = df.geometry.apply(lambda _geo: keep_first(_geo))
df.centroid