3

I'm trying to create a timeseries of raster data (one layer per year) by polygon (Administrative regions). Is there any way in QGIS to perform Zonal Statistics for multiple years (without having to perform the zonal statistics function each time)? Or something along the lines of the Point Sampling tool but for polygons?

  • Have you already tried to call the geoprocessing function from inside a for loop over years in Python console? – Detlev Jun 10 '15 at 17:28
1

I have something fairly close, although it only currently works for average and rejects max and min.

  1. Save all your raster layers in one folder with the same extension (e.g. .tif)
  2. Load shapefile (polygons) into QGIS
  3. Open Python (Plugins > Python console) and run the following

    import glob, os, qgis.analysis
    vectorlayer = qgis.utils.iface.mapCanvas().currentLayer()
    rasterfolder = 'C:/Users/…/Folder/'
    os.chdir(rasterfolder)
    for lyr in glob.glob("*.tif"):
        qgis.analysis.QgsZonalStatistics(vectorlayer, lyr, attributePrefix=lyr, rasterBand=1).calculateStatistics(None)
    

Using the vector layer loaded in QGIS was an easy way to append the results to the attribute table. The code to loop through rasters in a folder was from here.

If there is a way to specify the statistic using QgsZonalStatistics.Mean that would be helpful to know.

1

For mean only use

os.chdir(rasterfolder)
for lyr in glob.glob("*.tif") :
    qgis.analysis.QgsZonalStatistics(vector, lyr, attributePrefix=lyr, rasterBand=1, stats=QgsZonalStatistics.Statistics(QgsZonalStatistics.Mean)).calculateStatistics(None)
  • 1
    You should provide a little more text to say how this answers, or part answers the question – nmtoken Jan 2 '18 at 12: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.