Link Each Point In One Geopandas Dataframe To Polygons In Another Dataframe
I searched for my problem and found this question which is different from my issue. I have two geo data frames, one contains houses locations as points (~700 points) and the other
Solution 1:
I found a way to accomplish this by joining the two data frames using a spatial join
joinDF=gpd.sjoin(pointsDF, polysgdf, how='left',op="within")
Solution 2:
Use shapely's Point-in-Polygon analysis using .contains function as follows.
import geopandas as gpd
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
polys = gpd.GeoSeries({
'6672': Polygon([(0, 0), (0, 1), (1, 0)]),
'6372': Polygon([(0, 1), (1, 1), (1, 0)]),
})
#creating geo dataframe
polysgdf = gpd.GeoDataFrame(geometry=gpd.GeoSeries(polys))
polysgdf
Out[48]:
geometry
6672 POLYGON ((00, 01, 10, 00))
6372 POLYGON ((01, 11, 10, 01))
points=[Point(0.25,0.25), Point(0.75,0.75),
Point(145.02190, -37.85450)]
pointsDF = gpd.GeoDataFrame(geometry=points,
index=['house1_ID', 'house2_ID', 'house3_ID'])
pointsDF
Out[49]:
geometry
house1_ID POINT (0.250.25)
house2_ID POINT (0.750.75)
house3_ID POINT (145.0219 -37.8545)
polysgdf['house_ID'] = ''for i inrange(0,len(pointsDF)):
print('Check for house '+str(pointsDF.index.values.astype(str)[i]))
for j inrange(0,len(polysgdf)):
print('Check for suburb '+str(polysgdf.index.values.astype(str)[j]))
if polysgdf['geometry'][j].contains(pointsDF['geometry'][i]) == True:
polysgdf['house_ID'][j] = pointsDF.index.values.astype(str)[i]
print(polysgdf)
geometry house_ID
6672 POLYGON ((00, 01, 10, 00)) house1_ID
6372 POLYGON ((01, 11, 10, 01)) house2_ID
Post a Comment for "Link Each Point In One Geopandas Dataframe To Polygons In Another Dataframe"