3

How do I use zonal statistics in the python console to get CSV/dbf output?

I have used the code like this:

# Python code for Zonal statistics
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface
from qgis.analysis import QgsZonalStatistics
#specify polygon shapefile vector
polygonLayer = QgsVectorLayer(' E:/Trash/BhagaP.shp', 'zonepolygons', "ogr") 
# specify raster filename
rasterFilePath = 'E:/Trash/Test48P.img'
# usage - QgsZonalStatistics (QgsVectorLayer *polygonLayer, const QString &rasterFile, const QString &attributePrefix="", int rasterBand=1)
zoneStat = QgsZonalStatistics (polygonLayer, rasterFilePath, 'pre-', 1, QgsZonalStatistics.Mean)
zoneStat.calculateStatistics(None)
3

Your code works perfectly but, you cannot visualize changes immediately because it's necessary to add polygonLayer to registry. However, it can be loaded manually.

A simplified version of your code (where is loaded vector layer to registry) is as follows (with my paths):

from qgis.analysis import QgsZonalStatistics

#specify polygon shapefile vector
polygonLayer = QgsVectorLayer('/home/zeito/pyqgis_data/polygon1.shp', 
                              'polygon1', 
                              'ogr')

QgsMapLayerRegistry.instance().addMapLayer(polygonLayer)

# specify raster filename
rasterFilePath = u'/home/zeito/pyqgis_data/utah_demUTM12.tif'

# usage - QgsZonalStatistics (QgsVectorLayer *polygonLayer, const QString &rasterFile, const QString &attributePrefix="", int rasterBand=1)
zoneStat = QgsZonalStatistics (polygonLayer, rasterFilePath, 'pre-', 1, QgsZonalStatistics.Mean)
zoneStat.calculateStatistics(None)

After running it at Python Console of QGIS:

enter image description here

it can be observed that 'pre-mean' field was correctly added.

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.