【问题标题】:Return ZipCode if point in Polygon (shapely)如果点在多边形中,则返回 ZipCode(匀称)
【发布时间】:2015-11-22 22:27:06
【问题描述】:

我有一个带有一列点的 DataFrame A:

   points                      Code
0  Point(1.23, 1.34)            ?
1  Point(1.32, 3.56)            ?
2  Point(-1.09, 2.11)           ?
.
.

我还有另一个带有 Polygon 列的 DataFrame B:

   Code   Polygon
0  123    Polygon((-2,3),(1,4),(3,3),(-1,-2))
1  203    Polygon((-1,2),(0,2),(4,1),(-2,-1))
.
.

当点在多边形内时,如何将 B 中的代码传递给 A?

【问题讨论】:

    标签: python polygon shapely point-in-polygon spatial-data-frame


    【解决方案1】:

    假设你有两个数据框:

    df1 = GeoDataFrame(
        [[Point(1.23, 1.34)],
        [Point(1.32, 3.56)],
        [Point(-1.09, 2.11)]],
        columns=['geometry'],  
        geometry='geometry')
    
    df2 = GeoDataFrame(
        [[Polygon([(-2,3),(1,4),(3,3),(-1,-2)]), 123],
        [Polygon([(-1,2),(0,2),(4,1),(-2,-1)]), 203]],
        columns=['geometry', 'Code'],  
        geometry='geometry')
    

    您可以手动完成:

    # add the Code column:
    df1.loc[:,'Code'] = [None]*len(df1.geometry)
    # compute the intersections
    for i, p in enumerate(df1.geometry):
        for j, pol in enumerate(df2.geometry):
            if pol.contains(p):
                df1['Code'][i] = df2['Code'][j]
                break
    

    或者您可以使用空间连接来做到这一点:

    df1 = gpd.sjoin(df1, df2, how="inner", op='intersects')
    # remove the index_right extra column that is generated:
    df1.drop('index_right', axis=1, inplace=True)
    

    注意,如果一个点与多列相交,第二种方法会重复点行,第一种不会。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 2019-01-29
      • 2013-01-05
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      相关资源
      最近更新 更多