2

I have one shapefile with building polygons. I would like to convert them into lines split at each vertex, keeping the original source info as an attribute (Name).

    Name    category    height_ag   geometry
0   B10896  INDUSTRY    4   POLYGON ((489992.850 14287143.893, 489993.278 ...
1   B11115  SCHOOL_PT   4   POLYGON ((490120.908 14287231.826, 490122.609 ...
2   B11119  SCHOOL_PT   10  POLYGON ((490148.096 14287244.259, 490149.716 ...
3   B11148  SCHOOL_PT   10  POLYGON ((490139.029 14287275.704, 490131.278 ...
4   B10891  SCHOOL_PT   3   POLYGON ((490014.815 14287143.950, 490018.570 ...

I tried df.explode() from geopandas - but I believe it is not suitable for polygons. I know that QGIS does this for instance but I need to do it in Python

0

1 Answer 1

3

Use .boundary method to convert the polygons to lines, and .coords to fetch the coordinates of each line segment. Then .explode:

import geopandas as gpd
from shapely.geometry import LineString

df = gpd.read_file(r'/home/bera/Desktop/GIStest/buildings_con.shp')
df['geometry'] = df.geometry.boundary
dfline = gpd.GeoDataFrame(data=df, geometry='geometry')

def explodeLine(row):
    """A function to return all segments of a line as a list of linestrings"""
    coords = row.geometry.coords #Create a list of all line node coordinates
    parts = []
    for part in zip(coords, coords[1:]): #For each start and end coordinate pair
        parts.append(LineString(part)) #Create a linestring and append to parts list
    return parts
        
dfline['tempgeom'] = dfline.apply(lambda x: explodeLine(x), axis=1) #Create a list of all line segments
dfline = dfline.explode('tempgeom') #Explode it so each segment becomes a row (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html)

dfline = gpd.GeoDataFrame(data=dfline, geometry='tempgeom')
dfline = dfline.drop('geometry', axis=1)
dfline.crs = df.crs #Dont know why this is needed

enter image description here

0

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.