[Python] Dictionary of polygon sides/edges (including MultiPolygons)

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    This question is related to here.

    How do I create a dict of all the polygons [including MultiPolygons], in a GeoDataFrame, that share a side/edge. The polygons will intersect but never cross.

    polys = gpd.GeoSeries([Polygon([(0,0), (2,0), (2, 1.5), (2,2), (0,2)]),
    Polygon([(0,2), (2,2), (2,4), (0,4)]),
    Polygon([(2,0), (5,0), (5,1.5), (2,1.5)]),
    Polygon([(3,3), (5,3), (5,5), (3,5)]),
    MultiPolygon([Polygon([(6,1), (8, 1), (8, 3), (6, 3)],
    [[(6.5, 1.5), (7.5, 1.5), (7.5, 2.5), (6.5, 2.5)][::-1]]
    )])])

    fp = gpd.GeoDataFrame({'geometry': polys, 'name': ['a', 'b', 'c', 'd', 'e'],
    'grnd': [25, 25, 25, 25, 25],
    'rf': [29, 35, 26, 31, 28]})

    fig, ax = plt.subplots(figsize=(6, 6))
    fp.plot(ax=ax, alpha=0.3, cmap='tab10', edgecolor='k',)
    fp.apply(lambda x: ax.annotate(text=x['name'], xy=x.geometry.centroid.coords[0], ha='center'), axis=1)
    plt.show()


    [​IMG]

    I've tried this:

    # Create series of all the line segments
    lines = fp.geometry.apply(lambda x: (list(map(
    LineString,
    zip(x.boundary.coords[:-1], x.boundary.coords[1:])))
    if isinstance(x, MultiPolygon)
    else list(chain(*list(list(map(
    LineString,
    zip(x.boundary.coords[:-1], x.boundary.coords[1:])))
    for poly in x.geoms)))
    )).explode()

    result = {
    line : list(fp.loc[
    (fp.geometry.touches(line)) # line touches the polygon
    & (fp.geometry.intersection(line).length > 0), # And the intersection is more than just a point
    'rf'].values)
    for line in lines}



    which yields: AttributeError: 'Polygon' object has no attribute 'geoms'

    Expected result; something like:

    {'LINESTRING (0 0, 2 0)': ['a'],
    'LINESTRING (2 0, 2 1.5)': ['a', 'c'],
    'LINESTRING (2 1.5, 2 2)': ['a'],
    'LINESTRING (2 2, 0 2)': ['a', 'b'],
    'LINESTRING (0 2, 0 0)': ['a'],
    'LINESTRING (0 2, 2 2)': ['a', 'b'],
    'LINESTRING (2 2, 2 4)': ['b'],
    'LINESTRING (2 4, 0 4)': ['b'],
    'LINESTRING (0 4, 0 2)': ['b'],...}

    Continue reading...

Compartilhe esta Página