2

I have a geodataframe (download link) that contains the geometry of bus lines. It is a Multilinestring. I need to transform the geometry into a single Linestring.

My first idea was to use .explode (GeoPandas).

sel = gpd.read_file(".../sel_overflow.geojson")
exp_sel = sel
exp_sel.explode()

Result:

output

As you can see, the .explode() splitted the Multilinestring into two Linestrings.

Furthermore, I used shapely linemerge and I got the same Multilinestring back.

from shapely.ops import linemerge

geometry = sel.loc[0, 'geometry']
shapely_object = geometry  
line = linemerge(shapely_object)
gdf = gpd.GeoDataFrame(index=[0], crs='epsg:32718', geometry=[line])

output_2

1
  • 2
    If you wish to ask about doing this using PostGIS or R then please do that in a separate question and include a code attempt.
    – PolyGeo
    Commented Oct 13 at 6:26

1 Answer 1

3

You could brute force it by flattening the line parts with geometry.get_coordinates().

import geopandas as gpd
from shapely.geometry import  LineString

df = gpd.read_file("sel_overflow.geojson")
print(df.head())

df.geometry = df.geometry.apply(lambda geom: LineString(gpd.GeoSeries(geom).get_coordinates()))
print(df.head())

df.to_file("sel_overflow_single.geojson")

Output:

   OBJECTID                                           geometry
0       100  MULTILINESTRING ((265097.514 8665069.813, 2650...
   OBJECTID                                           geometry
0       100  LINESTRING (265097.514 8665069.813, 265046.3 8...

It won't work for something like the following though as a linestring can only have a single start and a single end point:

Y shape line. Attrib in link

2
  • Thanks for your answer. It works on some geometries, but it can't handle other MultiLineStrings that are similar to the one that you posted.
    – Daniel AG
    Commented Oct 13 at 11:04
  • 1
    That's right. Those can't be a converted to a linestring which can only have a single start and a single end point.
    – user2856
    Commented Oct 13 at 11:31

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.