简体   繁体   中英

Return ZipCode if point in Polygon (shapely)

I have a DataFrame A with a column of points:

   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:

   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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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