0

In the first column is a duplicate visible with identifica: 0225100000000012. these features have different field value in the 'layer' field, one has Utiliteit and another has Wtypes3. I want to delete the duplicate feature with the field value Utiliteit. How can i do this in PyQGIS?

Removing duplicate features based on a condition on another attribute column in QGIS

I found this answer but it is not working properly for me.

anwser: Removing duplicates from data attribute table by expression in QGIS

enter image description here

1 Answers1

0

You can use this snippet if the value of identifica is only duplicated once:

# Your layer
layer = iface.activeLayer()

value to delete = 'Utiliteit'

List of features id to remove after the test

features_to_select = []

List to check if the value of the field "identifica" has already been tested

value_tested = []

Every features are tested

for feature in layer.getFeatures():

If the value is not tested

if not feature["identifica"] in value_tested: # Check if there is a duplicate in the field "identifica" by selecting features layer.selectByExpression(" "identifica" = '{}' ".format(feature["identifica"])) if len(layer.selectedFeatureIds()) > 1: # If there is a duplicate, we check the value of the field "layer" if feature["layer"] == value_to_delete: # Feature id added to the list of if to remove features_to_select.append(feature.id()) # The value of the field "identifica" is added to the list value_tested.append(feature["identifica"])

Select features to remove by id

layer.selectByIds(features_to_select)

I suggest you to test the code using this part of the code, it will select the element to delete in your layer.

If the results are acceptable for you, you can add this at the end to delete the features:

# Delete all features in the list
layer.startEditing()
layer.deleteFeatures(features_to_select)
layer.commitChanges()
layer.triggerRepaint()
JULESG
  • 1,627
  • 3
  • 12