# Computing length of polygon segments using geopandas

I have this little issue I am trying to solve and I have looked everywhere for an answer. It seems odd that I cannot find it, but it might just be me.

So, I have this dataframe

``````df=
id     x_zone     y_zone
0  A1  65.422080  48.147850
1  A1  46.635708  51.165745
2  A1  46.597984  47.657444
3  A1  68.477700  44.073700
4  A3  46.635708  54.108190
5  A3  46.635708  51.844770
6  A3  63.309560  48.826878
7  A3  62.215572  54.108190
``````

that I convert into a `geopandas` dataframe:

``````df_geometry = gpd.GeoDataFrame(geometry=df.groupby('id').apply(
lambda g: Polygon(gpd.points_from_xy(g['x_zone'], g['y_zone']))))
df_geometry = df_geometry.reset_index()
print(df_geometry)
``````

which returns:

``````
id                                        geometry
A1  POLYGON ((65.42208 48.14785, 46.63571 51.16575...
A3  POLYGON ((46.63571 54.10819, 46.63571 51.84477...
``````

and for which I can compute the area and the perimeter:

``````df_geometry["area"] = df_geometry['geometry'].area
df_geometry["perimeter"] = df_geometry['geometry'].length
``````

which gives:

``````id                                           geometry       area  perimeter
0  A1  POLYGON ((65.42208 48.14785, 46.63571 51.16575...  72.106390  49.799695
1  A3  POLYGON ((46.63571 54.10819, 46.63571 51.84477...  60.011026  40.181476
``````

Now, to the core of my problem: IF one can calculate the length, surely the length of each segment of the polygons is being calculated. How can I retrieve this?

I understand that for very complicated polygons (e.g. country maps, this might be problematics to store). Anyone with an idea?

• There is no direct method in gp to do this as far as I know, but it seems to be pretty easy as you have the polygon string. Simply parse it to retrieve an array of numbers, they are already ordered so using indices 0-3, 2-5, 4-7 ..., grab those 4 numbers and calculate length of the segment. Commented Jun 10, 2021 at 11:06
• you can use `df_geometry.geometry.exterior[0].xy[0]` to get all x coordinates and `df_geometry.geometry.exterior[0].xy[1]` to get y coordinates as tuple and then calculate distance using Euclidean distance. Commented Jun 10, 2021 at 11:42
• @amanjain : This is brilliant! Post your answer and I'll accept is as accepted. I can fill with the method used thanks to your input. Commented Jun 10, 2021 at 11:58
• Euclidean distance of lat/lon values yields units of linear degrees, which are useless. Commented Jun 10, 2021 at 12:16
• @Vince all my points are in an area 100 m * 100 m. Euclidean distance is good enough. But you are absolutely right. I should have mentioned that. Commented Jun 10, 2021 at 12:20

You can use `df_geometry.geometry.exterior[0].xy[0]` to get all x coordinates and `df_geometry.geometry.exterior[0].xy[1]` to get y coordinates as tuple and then calculate distance using Euclidean distance.