# GeoPandas Spatial Join with random samples

I have a geopandas DataFrame with `Polygon` geometry and another one with `POINT` geometry. I'd like to do a spatial join between them and randomly select a set of `points` that are within certain distance or close to the polygon.

Here's some sample data:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=2c3c5863af9fe855491e4ef71f21a64b

Criteria:

Select `n` randomly sampled points from top `m` nearest points between `gpd2.geometry` (Point) to each `gpd1.geometry` (Polygon).

``````import geopandas as gpd
import numpy as np

gpd_merged = gpd.sjoin(
gpd1, # polygon geometry
gpd2, # point geometry (randomly sample and join)
how = 'left',
distance_col = "distances"
)
``````
• Can you also provide those points as you did with polygons ? Commented Jun 15, 2022 at 7:42
• Welcome to gis.stackexchange! Please note that a good question on this site is expected to show some degree of research on your part, i.e. what you have tried and - if applicable - code so far. For more info, you can check our faq. Commented Jun 15, 2022 at 18:50
• gis.stackexchange.com/help/someone-answers Commented Aug 28, 2023 at 7:09

The following will randomly sample n points within a specified distance of each poly.

It uses `gpd.sjoin_nearest` to assign all points to the closest polygon within a certain distance, then `groupby` and `sample` to randomly select the desired number of points per polygon.

``````import geopandas as gpd

max_distance = 0.1
n_points = 3

gdf_randomsample = gpd.sjoin_nearest(
gdf_points,       # point geometry
gdf_poly,         # polygon geometry
how='inner',      # drop points outside max_distance
max_distance=max_distance
).groupby("id_right").sample(n=n_points)
``````

Here's an example with your polygons (the buffer represents the specified max distance):

But note that the little polygon "ID" 2 gets no points assigned to it as all points are closer to the other polygons.