Tuesday, 5 May 2015

select by attribute - Deleting selected features using PyQGIS?



I have a shapefile with only one field DN. I would like to delete all features which does not have specific value of the field. Let's say the DN can be 1,2 or 3.


So far I was able to find out how to select Features and how to delete feature, but I did not succeed to combine them. Let's say I want only features with DN = 3 to remain:


Selection of the Features found here, however, I do not know if it does what it is supposed to do since I did not find the way how to check what is inside.


select = layer.getFeatures(QgsFeatureRequest().setFilterExpression(u'"DN"!=3'))

delete features found here


res = Ilayer.dataProvider().deleteFeatures()

As far as I know, the deleteFeatures() requires IDs of the features, but I have no idea how to get them from from select which is QgsFeatureIterator.



Answer




You can loop over the iterator and get the .id() for every feature in it:


with edit(layer):
# build a request to filter the features based on an attribute
request = QgsFeatureRequest().setFilterExpression('"DN" != 3')

# we don't need attributes or geometry, skip them to minimize overhead.
# these lines are not strictly required but improve performance
request.setSubsetOfAttributes([])
request.setFlags(QgsFeatureRequest.NoGeometry)


# loop over the features and delete
for f in layer.getFeatures(request):
layer.deleteFeature(f.id())

Or with QGIS < 2.12


request = QgsFeatureRequest().setFilterExpression('"DN" != 3')
request.setSubsetOfAttributes([])
request.setFlags(QgsFeatureRequest.NoGeometry)
ids = [f.id() for f in layer.getFeatures(request)]
layer.startEditing()

for fid in ids:
layer.deleteFeature(fid)
layer.commitChanges()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...