I have a shapefile with the Linestring elements which looks like this: enter image description here

Here you see a lot of small lines (about 582 in total). Is there a way to extract pure end-to-end lines? For now, I tried to combine Linestring elements together as the first step by the following code:

def connect_lineparts(geom_list):
    def dfs(adj_list, visited, vertex, result, key):
        for neighbor in adj_list[vertex]:
            if neighbor not in visited:
                dfs(adj_list, visited, neighbor, result, key)

    adj_list = defaultdict(list)
    for x, y in geom_list:

    result = defaultdict(list)
    visited = set()
    for vertex in adj_list:
        if vertex not in visited:
            dfs(adj_list, visited, vertex, result, vertex)
    return result

When I combine the result points together into Linestring I have something like this:

enter image description here

You can see there are some lines which were created by very distant points and absent of some small lines which were presented initially.

1 Answer 1


For doing this kind of thing in Python I would recommend looking into the Shapely library, where the linemerge command will combine chains of contiguous LineStrings into larger LineStrings.

If you want to extract 'pure end-to-end lines' you could use the unary_union command to merge all your lines into one MultiLineString, which will then consist of all the (merged) 'pure' lines.

  • Maybe I did something wrong, but the following script returns me 545 lines. That is too much: shapes = gpd.read_file(path).geometry.values merged = linemerge(shapes) Apr 21, 2022 at 7:24
  • @МаринаЛисниченко In what sense is it 'too much'? linemerge does not split up lines that cross, it only merges lines where the start of one coincides with the end of another. I expanded my answer with how you can split intersecting lines
    – Erik
    Apr 22, 2022 at 5:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.