I have a lot of coordinates in the attribute table like this one:
I'm looking for a way how to find and select active layer duplicated points using PyQGIS. I needn't delete them but only find and show (or select).
I have a lot of coordinates in the attribute table like this one:
I'm looking for a way how to find and select active layer duplicated points using PyQGIS. I needn't delete them but only find and show (or select).
This code should do the job (you need to have your layer activated before running it from the Python Console):
layer = iface.activeLayer()
allfeatures={}
index = QgsSpatialIndex()
for ft in layer.getFeatures():
allfeatures[ft.id()] = ft
index.insertFeature(ft)
selection = []
for feat in layer.getFeatures():
inGeom = feat.geometry()
idsList = index.intersects(inGeom.boundingBox())
if len(idsList) > 1:
for id in idsList:
selection.append(allfeatures[id])
layer.setSelectedFeatures([k.id() for k in selection])
File "<input>", line 7 layer.setSelectedFeatures([k.id() for k in selection]) ^ SyntaxError: invalid syntax
layer.setSelectedFeatures([k.id() for k in selection])
and it works great !
Here is another PyQGIS solution.
Let's assume there is a polygon layer called 'polygon' with its attribute table, see the image below.
Note: Features with the same "id"
possess the same geometry.
Proceed with Plugins > Python Console > Show Editor
and paste the script below:
# imports
from qgis.core import QgsProject
def select_features_with_duplicates(layer_name: str, reference_field: str) -> None:
"""
Selects features with duplicates in the reference field
:param layer_name: name of the layer
:param reference_field: name of the field to check e.g. id, fid etc.
"""
# get a layer by its name
layer = QgsProject.instance().mapLayersByName(layer_name)[0]
# list of all values of the reference field
all_values = layer.aggregate(aggregate=QgsAggregateCalculator.ArrayAggregate, fieldOrExpression=reference_field)[0]
# make a dict with duplicate values and times each occurred
dict_with_duplicates = {value : all_values.count(value) for value in all_values if all_values.count(value) > 1 }
# make a tuple of values from the dict keys
values_to_select = tuple([*dict_with_duplicates])
# selecting duplicate features by expression
expression = f'"{reference_field}" in {values_to_select}'
layer.selectByExpression(expression)
return
select_features_with_duplicates('polygon', "id")
Change the parameters of the function in the last line. Press Run script
and get the output that will look like this: