我有一個點的GeoDataFrame df_points(約50k)和一個多邊形的GeoDataFrame df_polygons(約50k)。
我希望通過保留df_points中的列來合并2個資料框架,并通過條件來匹配df_polygons中的列,即該點是否存在于多邊形中。
importgeopandas as gpd
from shapely.geometry import Point, Polygon
_polygons = [ Polygon([(5, 5), (5, 13), (13, 13), (13, 5)] )。多邊形([(10, 10), (10, 15), (15, 15), (15, 10) ]) ]
_pnts = [Point(3, 3), Point(8, 8), Point(11, 11) ]
df_polygons = gpd.GeoDataFrame(geometry=_polygons, index=['foo', 'bar'])。
df_points = gpd.GeoDataFrame(geometry=_pnts, index=['A', 'B', 'C']).reset_index()
df_points看起來是:
> df_points
索引幾何
0一個點(3.00000 3.00000)
1 B點(8.00000 8.00000)
2 C點(11.00000 11.00000)
df_polygons看起來是:
> df_polygons
索引幾何
0 foo POLYGON ((5.00000 5。 00000, 5.00000 13.00000, 1..
1 bar POLYGON ((10.00000 10.00000, 10.0000015.00000...
結果可能看起來像:
index geometry_points geometry_index geometry_polygons
0一個點(3.00000 3.00000) [] []
1 B點(8.00000 8.00000) ['foo'] [Polygon([(5, 5), (5, 13), (13, 13), (13, 5) ])
2 C點(11.00000 11.00000) ['foo','bar'] [多邊形([(5, 5), (5, 13), (13, 13), (13, 5)] )。多邊形([(10, 10), (10, 15)。(15, 15), (15, 10) ]]
是否有辦法有效地合并資料幀?
uj5u.com熱心網友回復:
使用空間連接(gpd.sjoin):
# Rename 'index' columns to avoid FutureWarning
dfp = df_points.rename(columns={'index': 'point'})
dfa = df_polygons.rename(columns={'index': '區域'})
# 查找多邊形內的點。
out = gpd.sjoin(dfp, dfa, how='inner', op='within')
# 減少行數'point')
.agg({' area': lambda x: x.tolist() if x.any() else [ ] 。
'index_right': lambda x: dfa.loc[x, 'geometry'] .tolist()
if ~x.all() else []})
.reset_index()
# Append columns[/span
dfp = dfp.merge(out, on='point')
輸出:
>>> dfp
點的幾何面積 index_right
0 A POINT (3.00000 3.00000) [] []
1 B點(8.00000 8.00000) [foo] [POLYGON((5 5, 5 13, 13 13, 13 5, 5) ]]
2 C點(11.00000 11.00000) [foo, bar] [POLYGON ((5 5, 5 13, 13 13, 13 5, 5 5)), POLY。 ..
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326826.html
標籤:
