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

6
  • what have you tried so far? where are you stuck?
    – Ian Turton
    Commented Sep 13, 2022 at 14:27
  • I found this code online, i don't fully understand it with the 'dictionary' Commented Sep 13, 2022 at 14:42
  • Welcome to GIS SE! We're a little different from other sites; this isn't a discussion forum but a Q&A site. Your questions should as much as possible describe not just what you want to do, but precisely what you have tried and where you are stuck trying that. Please check out our short tour for more about how the site works
    – Ian Turton
    Commented Sep 13, 2022 at 15:14
  • Is it always the case, that if there are duplicates on identifica you want to keep Utiilitei?
    – Bera
    Commented Sep 13, 2022 at 15:54

1 Answer 1

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()

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.