I am attempting to use the following code to calculate standard deviation:

QgsZonalStatistics (QgsVectorLayer *polygonLayer, QgsRasterLayer *rasterLayer, const QString &attributePrefix="", int rasterBand=1, QgsZonalStatistics::Statistics) 

But it is only giving mean and count. How do I get SD?

  • In my answer you have a complete code for getting only standard deviation or all statistics. – xunilk Jul 4 '17 at 13:54

For this situation:

enter image description here

complete code for getting only standard deviation is:

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.StDev)


If you want all statistics, change suffix StDev for All.

After running the code at Python Console of QGIS, attributes table now shows a new calculated statistic.

enter image description here


have a look at the API documentation for QgsZonalStatistics. There is stated, that you can use flags to indicate which statistic you want to include. A complete list can be found in this section.

So you would do something like this:

myRasterLayer = 'C\path\to\raster\my_raster.tif'
QgsZonalStatistics(myPolyLayer, myRasterLayer, "prefix", 1,     stats = Statistics( Count | Sum | Mean| StDev) )

Where myPolyLayer is your input Polygone, myRasterLayer is the path to your raster file from which you want to get the statistics, prefix a prefix for your attributes (can be empty), 1 stands for the rasterband you are looking in and stats determine the flags.

  • using zonalstats =qgis.analysis.QgsZonalStatistics(vectorlayer, rasterfile, 'zo_', 1, QgsZonalStatistics::( Count | Sum | Mean| StDev) ) zonalstats.calculateStatistics(None) but showing error – User18 Jul 3 '17 at 7:17
  • @User18 could you add the error msg to your question so we can have a look? – LaughU Jul 3 '17 at 7:22
  • Error: AttributeError: type object 'QgsZonalStatistics' has no attribute 'statistics' – User18 Jul 3 '17 at 7:24
  • 1
    @LaughU Your proposal doesn't work because second parameter must be a path to raster layer (not a QgsRasterLayer object). – xunilk Jul 4 '17 at 14:03
  • 1
    @xunilk thanks for your input :) I changed my answer accordingly – LaughU Jul 4 '17 at 14:21

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.