You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建GeoDataFrame中顶点关联多边形的dict字典

实现顶点与关联多边形的字典映射(GeoDataFrame场景)

需求说明

创建一个字典,用于存储GeoDataFrame中每个顶点对应的关联多边形,这些多边形仅相交但不交叉。

示例数据与可视化

示例代码

import geopandas as gpd
from shapely.geometry import Polygon
import matplotlib.pyplot as plt

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)])])

fp = gpd.GeoDataFrame({'geometry': polys, 'name': ['a', 'b', 'c', 'd']})

fig, ax = plt.subplots(figsize=(5, 5))
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()

可视化效果

多边形可视化

当前顶点遍历代码

for i, row in fp.iterrows():
    oring = list(row.geometry.exterior.coords)
    if row.geometry.exterior.is_ccw == False:
        # 调整方向以获取正确的法线朝向
        oring.reverse() 
    for (j, v) in enumerate(oring[:-1]):
        print([oring[j][0], oring[j][1], row['name']])

当前输出结果

[0.0, 0.0, 'a']
[2.0, 0.0, 'a']
[2.0, 1.5, 'a']
[2.0, 2.0, 'a']
[0.0, 2.0, 'a'] 
[0.0, 2.0, 'b']  
[2.0, 2.0, 'b']  
[2.0, 4.0, 'b']  
[0.0, 4.0, 'b']
[2.0, 0.0, 'c']
[5.0, 0.0, 'c']
[5.0, 1.5, 'c']
[2.0, 1.5, 'c']
[3.0, 3.0, 'd']  
[5.0, 3.0, 'd']  
[5.0, 5.0, 'd']  
[3.0, 5.0, 'd']

预期结果

每个顶点对应的关联多边形如下:

  • 顶点(0.0, 0.0):a
  • 顶点(2.0, 0.0):a、c
  • 顶点(2.0, 1.5):a、c
  • 顶点(2.0, 2.0):a、b
  • 顶点(0.0, 2.0):a、b
  • 顶点(0.0, 2.0):b、a
  • 顶点(2.0, 2.0):b、a
  • 顶点(2.0, 4.0):b
  • 以此类推

解决方案代码

# 初始化存储顶点与多边形映射的字典
vertex_polygon_map = {}

for i, row in fp.iterrows():
    poly_name = row['name']
    oring = list(row.geometry.exterior.coords)
    if not row.geometry.exterior.is_ccw:
        oring.reverse()
    
    # 遍历每个顶点(排除最后一个,因为首尾重合)
    for v in oring[:-1]:
        # 将顶点坐标转为元组(列表不可哈希,不能作为字典键)
        vertex_key = (v[0], v[1])
        # 如果顶点已在字典中,追加多边形名称;否则创建新条目
        if vertex_key in vertex_polygon_map:
            vertex_polygon_map[vertex_key].append(poly_name)
        else:
            vertex_polygon_map[vertex_key] = [poly_name]

# 打印结果
for vertex, polys in vertex_polygon_map.items():
    print(f"顶点{vertex}对应:{'、'.join(polys)}")

输出验证

运行上述代码后,输出将符合预期:

顶点(0.0, 0.0)对应:a
顶点(2.0, 0.0)对应:a、c
顶点(2.0, 1.5)对应:a、c
顶点(2.0, 2.0)对应:a、b
顶点(0.0, 2.0)对应:a、b
顶点(2.0, 4.0)对应:b
顶点(0.0, 4.0)对应:b
顶点(5.0, 0.0)对应:c
顶点(5.0, 1.5)对应:c
顶点(3.0, 3.0)对应:d
顶点(5.0, 3.0)对应:d
顶点(5.0, 5.0)对应:d
顶点(3.0, 5.0)对应:d

内容的提问来源于stack exchange,提问作者arkriger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:07:13