2

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.

  • `LINESTRING ((0 0), (1 1), (2 2))` is the string wkt encoding of the python object in the first line of your question, right? Are you asking how to convert from a wkt string to a shapely linestring? – Michael Delgado Dec 18 '21 at 18:04
  • If not, it's not clear what it is you're trying to do and where you're stuck. Please clarify in python what you are doing now, what's not working, and what you're trying to do, ideally as a [MRE]. Thanks! – Michael Delgado Dec 18 '21 at 18:06

1 Answers1

2

'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>
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Thanks for the answer. It answers the question as it was posed. And you are right, ```'LINESTRING ((0 0), (1 1), (2 2))'``` is not a valid wkt and it is not what I have in my df. It is actually, ```'LINESTRING (0 0, 1 1, 2 2)'```. – Serge de Gosson de Varennes Dec 19 '21 at 08:18
  • But, I still cannot get from ```'LINESTRING (0 0, 1 1, 2 2)'``` to ```LineString([(0, 0), (1, 1), (2, 2)])```. Basically, I want to convert the entire column of the first type into the other. – Serge de Gosson de Varennes Dec 19 '21 at 08:24