Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a polygon layer with bounding boxes (boundingLayer). This layer has attribute columns "HEIGHT" and "WIDTH". I want to delete all bounding boxes which have HEIGHT and WIDTH less than 200m. How should I proceed?

boundingLayer = QgsVectorLayer("/home/usr/Desktop/BoundingBoxes.shp", "BoundingBoxes", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(boundingLayer)
provider = boundingLayer.dataProvider()
updateMap = {}
# To find the right id of the fields I need:
idHeight = provider.fields().indexFromName( 'HEIGHT' )
idWidth = provider.fields().indexFromName( 'WIDTH' )
iter = provider.getFeatures()
for feature in iter:
    Height = feature.attributes()[idHeight]
    Width = feature.attributes()[idWidth]
    if Height < 200: 
    ..............
share|improve this question
    
Is the relationship between the polygon layer and boundingLayer only spatial, or is there an attribute (e.g. ID) shared by both layers? – ArMoraer Feb 19 at 13:24
    
I am sorry, I was probably not clear. I have a shape file containing bounding boxes created using processing.runalg('qgis:polygonfromlayerextent' ...) In the current script I am only working on the shape file with the bounding boxes, the layer with the polygons is not relevant anymore. The idea is for me to delete all bounding boxes with height and width less than 200 m so that I can later clip my polygon layer. – ELD Feb 19 at 13:27
    
Ok, added an answer then. – ArMoraer Feb 19 at 13:46
    
simply look at Delete Features in Using Vector Layers – gene Feb 19 at 15:20
up vote 3 down vote accepted

If you just want to delete a feature (bounding box), that's easy:

for feature in iter:
    height = feature['HEIGHT']
    width = feature['WIDTH']    
    if (height < 200) and (width < 200):
        provider.deleteFeatures( [feature.id()] )

Don't forget to call commitChanges() when you're done with all the deleting:

boundingLayer.commitChanges()
share|improve this answer

Just to provide an alternative to @ArMoraer's great answer, you could also use the following:

boundingLayer = QgsVectorLayer("/home/usr/Desktop/BoundingBoxes.shp", "BoundingBoxes", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(boundingLayer)
with edit(boundingLayer):
    request = QgsFeatureRequest().setFilterExpression(u'"HEIGHT" < 200 AND "WIDTH" < 200')
    ids = [f.id() for f in layer.getFeatures(request)]
    for fid in ids:
        layer.deleteFeature( fid )
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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