1

I need to write QGIS script, which removes features with same value of specific attribute - in output will be only features with first occurrence of value. I know, how to check duplicity, but I don't know, how properly create output from my script, when I need it to use in graphical modeler.

Also, what is the best way to get input into the script?

I am beginer in QGIS scripting, but I noticed that the basic scripts deal with inputs differently than any downloaded user scripts (which follow this documentation: https://docs.qgis.org/2.6/en/docs/user_manual/processing/scripts.html).

  • 1
    Last time I looked QGIS used QT forms, though I suppose any UI for python would work. Is this running as an add-in? – Michael Stimson Jun 12 '15 at 2:42
1

The following script can be used in the Processing Toolbox (either directly or through the modeler) which allows the user to select a field in the relevant layer and will only output the features with values which occur first:

##Delete first occurence=name
##input=vector
##field=field input
##output=output vector

from qgis.core import *

layer = processing.getObject(input)
provider = layer.dataProvider()
fields = provider.fields()
writer = QgsVectorFileWriter(output, 'UTF-8', fields, provider.geometryType(), layer.crs(), "ESRI Shapefile")

in_feat = QgsFeature()
out_feat = QgsFeature()
geom = QgsGeometry()
values = {}

value_field_index = layer.fieldNameIndex(field)

for in_feat in layer.getFeatures():
    geom = in_feat.geometry()
    attrs = in_feat.attributes()
    value = attrs[value_field_index]

    if value not in values:
        values[value]=[]
        out_feat.setGeometry(geom)
        out_feat.setAttributes(attrs)
        writer.addFeature(out_feat)

del writer

  • Attributes of input layer:

    Before script

  • Attributes of output layer:

    After script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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