GeoPandas – Counting Number of Vertices in GeoDataFrame

geopandaspython

Is there any method to count number of vertices of polygon (or multipolygon etc.) that is in 'geometry' column in datatable, but using GeoPandas?

Example:

Let's say I have polygon

POLYGON ((552971.4480249976 155085.9494381994, 552975.0980249938 155093.2494382081, 552980.7980249878 155104.5994382233, 552981.8480249867 155106.6494382256, 552986.8670249796 155118.8284382395, 552993.9820249865 155114.5394382458, 552992.3430249887 155110.6504382399, 552989.1980249948 155100.8494382298, 552983.1480250009 155089.1494382163, 552982.6980250012 155088.5494382135, 552981.3860250067 155080.7984382049, 552971.4480249976 155085.9494381994))

After loading shapefile and iterating over lines of data using iterrows() method, how to count that this polygons is made from e.g. 41 points, another on 30 etc. Maybe there is some function like .length or .area?

Best Answer

goepandas uses shapely package for geometry. As far as I know, shapely has no any function that shows number of vertices like geometry.vertices or len(geometry) etc. But you can implicitly get the number of vertices of any geometry.

import geopandas as gp
df = gp.read_file("shapefile_path")

for i, row in df.iterrows():
    # It's better to check if multigeometry
    multi = row.geometry.type.startswith("Multi")

    if multi:
        n = 0
        # iterate over all parts of multigeometry
        for part in row.geometry:
            n += len(part.exterior.coords)
    else: # if single geometry like point, linestring or polygon
        n = len(row.geometry.exterior.coords)

    print(n)

If you want to add number of vertices as a column into df, try in that way:

import geopandas as gp
df = gp.read_file("shapefile_path")

n_vertices=[] ###

for i, row in df.iterrows():
    # It's better to check if multigeometry
    multi = row.geometry.type.startswith("Multi")

    if multi:
        n = 0
        # iterate over all parts of multigeometry
        for part in row.geometry:
            n += len(part.exterior.coords)
    else:
        n = len(row.geometry.exterior.coords)
    n_vertices.append(n) ###


df["n_vertices"] = n_vertices ###
df.to_file("new_shapefile_path") ###

# EXAMPLE
#                                           geometry        n_vertices
#  0    POLYGON ((3241688.46003131 4980597.749317063, ...   6
#  1    POLYGON ((3241575.693387136 4980461.03521121, ...   5

EDIT: This method just counting vertices of exterior ring(s), it doesn't take account of holes (interior ring(s)).