QGIS – Selecting Only One Point within a Polygon

pointpoint-in-polygonpolygonqgisselect-by-location

I have two shapefiles: polygon(buffer) and point.

How can I select only one point in each buffer in QGIS?

If I use the "Select by Location", I will get all points inside the polygons, however I need only one? It doesn't matter which point out of two or more in polygon is selected.

enter image description here

Best Answer

If you don't care which point is selected, you can use this small PyQGIS script. Paste into a blank editor in the Python Console, change the layer names in the first two lines to match your layer names and click run.

# Change layer names in the first two lines to match your layers...
point_lyr = QgsProject.instance().mapLayersByName('New scratch layer')[0]
poly_lyr = QgsProject.instance().mapLayersByName('Buffered')[0]

ids = []

for feat in poly_lyr.getFeatures():
    contained_point = [f for f in point_lyr.getFeatures() if f.geometry().within(feat.geometry())][0]
    ids.append(contained_point.id())

point_lyr.selectByIds(ids)

Result:

enter image description here