Created
September 9, 2020 17:09
-
-
Save aSipiere/d4d88d07d1952627d31e1b86fbeaaa45 to your computer and use it in GitHub Desktop.
get nearest point geopandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import geopandas as gpd | |
from shapely.ops import nearest_points | |
def nearest(row, df1, df2, geom1_col='geometry', geom2_col='geometry', src_column=None): | |
"""Find the nearest point and return the corresponding value from specified column.""" | |
# Construct a multipoint object | |
geom_union = df2.unary_union | |
# Find the geometry that is closest | |
nearest = df2[geom2_col] == nearest_points(row[geom1_col], geom_union)[1] | |
# Get the corresponding value from df2 (matching is based on the geometry) | |
value = df2[nearest][src_column].values[0] | |
return value | |
a_df = gpd.GeoDataFrame() | |
b_df = gpd.GeoDataFrame() | |
a_df['nearest_id'] = a_df.apply(nearest, df1=a_df, df2=b_df, src_column='id', axis=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment