I've got two geopandas geodataframes. One is a series of points of locations. Locations of bus stops, for example. Let's call it bus_stops
I've then got another geodataframe where geometry column is polygons of geometries, say wards within a UK county. Let's call that wards.
I can combine the wards into county_boundary like so:
county_boundary = wards.unary_union
What I want to do is calculate the distance of each of the points to the boundary.
If I check type:
type(wards.unary_union)
I get
shapely.geometry.multipolygon.MultiPolygon
The problem is that if I try to calculate that using .distance in geopandas it returns 0.
bus_stops['dist_to_edge'] = bus_stops.geometry.apply(lambda g: county_boundary.distance(g))
I can see that because the points are within the space then the distance should be 0.
How do I flip the county_boundary so that it is the inverse of county_boundary?
Or is there a better of calculating this sort of thing? It would appear to be quite a common thing to do with maps?
Apologies for lack of data.
Replace the polygon geometries with their boundaries, and calculate distance with sjoin_nearest
:
import geopandas as gpd
ward = gpd.read_file(r"D:/gisdata/LMV/LMV-data_2021-10/ok_riks_Sweref_99_TM_shape/oversikt/riks/nv_riks.shp")
bus_stops = gpd.read_file(r"C:/Users/bera/Desktop/gistest/One_hundred_points.gpkg")
ax = ward.plot(figsize=(10,10), zorder=1, color="lightgreen")
bus_stops.plot(ax=ax, zorder=2, color="blue")
ward["geometry"] = ward.boundary
ward.plot(ax=ax, zorder=2, color="red", linewidth=3)
#Join nearest ward to each point and add a distance column namned poly_dist. Adjust max distance.
bus_stops = gpd.sjoin_nearest(left_df=bus_stops, right_df=ward,
how="left", max_distance=20000, distance_col="poly_dist")
# bus_stops.head()
# id geometry ... ADAT poly_dist
# 0 0 POINT (649942.671 7327725.077) ... 2009-10-21 13:30 6185.170242
# 1 1 POINT (646615.769 7311022.933) ... 2012-10-19 13:23 5330.508619
# 2 2 POINT (705369.155 7299663.452) ... 2012-09-05 15:26 5168.932173
# 3 3 POINT (693101.929 7314997.21) ... 2019-01-24 11:40 4372.310940
# 4 4 POINT (702556.462 7321845.72) ... 2012-09-05 15:01 4314.514846