简体   繁体   English

如果多边形中的点(匀称)返回ZipCode

[英]Return ZipCode if point in Polygon (shapely)

I have a DataFrame A with a column of points: 我有一个带有点列的DataFrame A:

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

I also have another DataFrame B with a column of Polygon: 我还有另一个带有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))
.
.

How can I pass the Code in B to A when the point is within Polygon? 当点在多边形内时,如何将B中的代码传递给A?

Suppose you have the two dataframes: 假设您有两个数据框:

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

You can do it manually: 您可以手动执行以下操作:

# 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

Or you can do it with spacial join: 或者,您可以通过空间连接来实现:

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)

Beware, the second method will repeat the point rows if a point intersects more than one column, the first one will not. 当心,如果一个点与一个以上的列相交,第二种方法将重复这些点的行,而第一个则不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM