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:



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"
  • 1
    Can you also provide those points as you did with polygons ?
    – Taras
    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.
    – underdark
    Commented Jun 15, 2022 at 18:50
  • gis.stackexchange.com/help/someone-answers
    – user2856
    Commented Aug 28, 2023 at 7:09

1 Answer 1


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

gdf_points = gpd.read_file(points)
gdf_poly = gpd.read_file(polys)

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

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

enter image description here

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

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.