PyQGIS Zonal Statistics – Fix “AttributeError: ‘QgsZonalStatistics’ Object has No Attribute ‘getFeatures'”

attributeerrorfilterpyqgisrasterzonal statistics

I want to calculate zonal stats of a raster using a polygon layer and the filter the ouput as another layer.

This is the code I tried:

zoneStat = QgsZonalStatistics (tempVectorLyr, rasterLyr, '-', 1)
zoneStat.calculateStatistics(None)

count = math.ceil(thresholdArea / (abs(xres) * abs(yres)))

features = zoneStat.getFeatures("\"_sum\">{}".format(count))

featureLayer = QgsVectorLayer("Polygon", "Flayer", "memory")
    featureLayer.setCrs(r_crs)
    pr = featureLayer.dataProvider()

    no_f = 0
    for feature in features:
        no_f = no_f + 1
        pr.addFeature(feature)

This was the error I got:

AttributeError: 'QgsZonalStatistics' object has no attribute
'getFeatures'

I'm guessing zoneStat is not a layer, how do I save it as memory layer?

Best Answer

I'm guessing zoneStat is not a layer

No it's not. Your zoneStat variable is an instance of the QgsZonalStatistics class. When you call its method calculateStatistics(), what is returned is an enumerator code which corresponds to either success or one of several errors.

See documentation here.

If the calculation method is successful, the important thing to understand is that the statistics fields will be added to your input vector layer which you passed to the instance of QgsZonalStatistics in the class constructor (which in your case already appears to be a temporary memory layer), so once the calculation has run and returned 0, you can filter your input layer directly.

I would modify your code slightly to something like:

...
zoneStat = QgsZonalStatistics (tempVectorLyr, rasterLyr, '_', 1)
result = zoneStat.calculateStatistics(None)
if result == 0:
    count = math.ceil(thresholdArea / (abs(xres) * abs(yres)))
    features = tempVectorLyr.getFeatures("\"_sum\">{}".format(count))
    # do something with features
...

One other thing: There is a typo in your code- When you instantiated the QgsZonalStatistics class you passed '-' (a hyphen), as the field prefix character, but later in your getFeatures() expression your field name is prefixed with an underscore.