2015-11-22 39 views
1

我有一個數據幀A和點的列點:返回郵編,如果在多邊形(勻稱)

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

我也有另外一個數據幀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嗎?

回答

0

假設你有兩個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') 

您可以手動做到這一點:

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

當心,該如果一個點與多列相交,第二種方法將重複點行,第一種方法不會。

相關問題