[1127] Find the closest point to each polygon
You can use sjoin_nearest() from geopandas to find the closest point to each polygon. Here's how:
Example Code
import geopandas as gpd
# Ensure both GeoDataFrames have the same CRS
gdf_point = gdf_point.to_crs(gdf_polygon.crs)
# Perform spatial join to find the nearest point for each polygon
gdf_nearest = gpd.sjoin_nearest(gdf_polygon, gdf_point, how="left", distance_col="distance")
print(gdf_nearest.head())
Explanation
sjoin_nearest()finds the closest point for each polygon.how="left"ensures all polygons are retained, even if no point is found.distance_col="distance"adds a column showing the distance between the polygon and its nearest point.
The results of the above geoprocessing may have multiple matches. Therefore, duplicate records should be removed.
You can remove duplicates from your DataFrame and keep only the first occurrence using pandas:
Drop Duplicates While Keeping the First Row
df_unique = df.drop_duplicates(subset=["column_name"], keep="first")
Explanation
subset=["column_name"]specifies the column to check for duplicates.keep="first"ensures that the first occurrence is retained, while others are dropped.
浙公网安备 33010602011771号