0

I have a graph in Python GeoPandas with many connected components. And I want to create a graph with only one connected component.

Does there exist some convenience functions to fill the gaps in GeoPandas?

  • 2
    Sorry, but unless you add a code attempt your question will be closed – gene Oct 26 at 16:21
  • 2
    And a screenshot would help – BERA Oct 26 at 17:14
1

This is an implementation which requires pygeos, but it is fast. Notice that it does not preserve any attributes as it works on numpy array of pygeos geometries.

See details on pygeos backed in geopandas - https://geopandas.readthedocs.io/en/latest/getting_started/install.html#using-the-optional-pygeos-dependency

def close_gaps(df, tolerance):
    """Close gaps in LineString geometry where it should be contiguous.
    Snaps both lines to a centroid of a gap in between.
    """
    geom = df.geometry.values.data
    coords = pygeos.get_coordinates(geom)
    indices = pygeos.get_num_coordinates(geom)

    # generate a list of start and end coordinates and create point geometries
    edges = [0]
    i = 0
    for ind in indices:
        ix = i + ind
        edges.append(ix - 1)
        edges.append(ix)
        i = ix
    edges = edges[:-1]
    points = pygeos.points(np.unique(coords[edges], axis=0))

    buffered = pygeos.buffer(points, tolerance)

    dissolved = pygeos.union_all(buffered)

    exploded = [
        pygeos.get_geometry(dissolved, i)
        for i in range(pygeos.get_num_geometries(dissolved))
    ]

    centroids = pygeos.centroid(exploded)

    snapped = pygeos.snap(geom, pygeos.union_all(centroids), tolerance)

    return snapped

Source of the function: https://github.com/urbangrammarai/spatial_signatures/blob/4c71c16940ebe695b3765a98041d326e73113a46/spatial_unit/snap.py#L209

| improve this answer | |
1

If I understand correctly, you have small gaps in your line (or disconnected lines). You need to find those lines, use geopandas to find the nearest geometries within a buffer, then use shapely.ops nearest_point. Then gap the bridge between both geometries.

| improve this answer | |

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