Shapely – How to Explode LineString into Segments in Python

explodegeopandaslinestringpythonshapely

I am trying to find explode lines tool in QGIS equivalent in shapely or geopandas (which uses shapely anyway). does anyone know this?

note that geopandas.GeoDataFrame.explode() does not work because it converts multilinestring into linestring which is not the issue.

Suppose I have a LineString:

'LINESTRING ((0,0),(0,1),(0,2),(0,3),(0,4))'

How do I explode this into

'LINESTRING ((0,0),(0,1))'
'LINESTRING ((0,1),(0,2))'
'LINESTRING ((0,2),(0,3))'
'LINESTRING ((0,3),(0,4))'

Best Answer

line = LineString(((0,0),(0,1),(0,2),(0,3),(0,4)))
print(list(line.coords))
[(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (0.0, 3.0), (0.0, 4.0)]
for pt1,pt2 in zip(line.coords, line.coords[1:]):
    print(LineString([pt1,pt2]))

LINESTRING (0 0, 0 1)
LINESTRING (0 1, 0 2)
LINESTRING (0 2, 0 3)
LINESTRING (0 3, 0 4)

Or

def pair(list):
   '''Iterate over pairs in a list '''
   for i in range(1, len(list)):
          yield list[i-1], list[i]

for pt1,pt2 in pair(line.coords):
     print(LineString([pt1,pt2]))

LINESTRING (0 0, 0 1)
LINESTRING (0 1, 0 2)
LINESTRING (0 2, 0 3)
LINESTRING (0 3, 0 4)