[GIS] Problem with calculating QGIS Zonal Statistics MEAN

pyqgisqgiszonal statistics

I need to calculate some zonal statistics from raster files for some polygons in a shapefile. I am using the following code which works:

    eligibleLayer = QgsVectorLayer("/home/usr/Desktop/polygons.shp", "polygons", "ogr")
    for raster in findRasters(windMapsDirectory, '*.tif'):
        (infilepath, infilename) = os.path.split(raster) 
        windMapName = infilename
        list1 = re.split('\W+',windMapName)
        list2 = re.split("_", list1[0])
        list3 = list2[2]
        string1 = ''.join(list3)
        if string1 == 'K':
            zoneStat = QgsZonalStatistics(eligibleLayer, windMapName, 'K_', 1)
            zoneStat.calculateStatistics(None)

The problem is that I only need the mean from the zonal statistics (no count and sum). I tried using:

        if string1 == 'K':
            zoneStat = QgsZonalStatistics(eligibleLayer, windMapName, 'K_', 1, QgsZonalStatistics.Mean)

However, I get the following error: type object 'QgsZonalStatistics' has no attribute 'Mean' . I am using QGIS 2.8.6.

Best Answer

For some reason your code is not producing a QgsZonalStatistics object. Print 'zoneStats' to corroborate this. It should be observed some similar to:

<qgis._analysis.QgsZonalStatistics object at 0x9fc316ec>

I tried out the next code:

from qgis.analysis import QgsZonalStatistics

mapcanvas = iface.mapCanvas()

layers = mapcanvas.layers()
provider = layers[1].dataProvider()

path = provider.dataSourceUri()

zoneStat = QgsZonalStatistics(layers[0], path,"", 1, QgsZonalStatistics.Mean)

print zoneStat

zoneStat.calculateStatistics(None)

for this situation:

enter image description here

and, after running the script, it was added only the mean value; as it can be observed at the next image:

enter image description here

It works perfectly for me.

Related Question