Convert LINESTRING wkt representation LINESTRING((a b),(c d)) to LineString[(a,b),(c,d)]

Viewed 590

I know how to go from

line = LineString([(0, 0), (1, 1), (2, 2)])

to

LINESTRING ((0 0), (1 1), (2 2))

But not the other way around. How do I do this?

The reason I need to do this is that I want to be able to apply the following function to split my LINESTRINGS into it sides.

from shapely.geometry import LineString, LinearRing

def segments(curve):
    return list(map(LineString, zip(curve.coords[:-1], curve.coords[1:])))


line = LineString([(0, 0), (1, 1), (2, 2)])

line_segments = segments(line)
for segment in line_segments:
    print(segment)

and it cannot be applied to wkt representations of linestrings.

1 Answers

'LINESTRING ((0 0), (1 1), (2 2))' is not a valid WKT strings. For your example the correct representation should be 'LINESTRING (0 0, 1 1, 2 2)' without inner parentheses.

To convert from a format to another, use dumps/loads from shapely.wkt module:

from shapely.geometry import LineString
import shapely.wkt

line = LineString([(0, 0), (1, 1), (2, 2)])
str_line = shapely.wkt.dumps(line)

print(shapely.wkt.loads(str_line) == line)

# Output:
True

Update: if you want to parse a such string, use a regex to remove inner parentheses:

s = 'LINESTRING ((0 0), (1 1), (2 2))'
str_line = re.sub(r'\(([^()]*)\)', r'\1', s)

print(shapely.wkt.loads(str_line) == line)

# Output:
True

Update 2: This doesn't work?

import pandas as pd
import shapely.wkt

df = pd.DataFrame({'lines': ['LINESTRING (0 0, 1 1, 2 2)']})
df['lines2'] = df['lines'].apply(lambda x: shapely.wkt.loads(x))

Output:

>>> df
                        lines                      lines2
0  LINESTRING (0 0, 1 1, 2 2)  LINESTRING (0 0, 1 1, 2 2)

>>> df.loc[0, 'lines']
'LINESTRING (0 0, 1 1, 2 2)'

>>> df.loc[0, 'lines2']
<shapely.geometry.linestring.LineString at 0x7fa386735a30>
Related