1

Has anybody successfully used Zonal statistics in a loop in QGIS 3.8?

I have to go through several rasters using a vector file.

Batch processing seems to fail in QGIS 3.8 too - see Zonal statistics using Python console in QGIS gives AttributeError?

  • 3
    Are you trying to do this using PyQGIS now? If so, what does your current code look like? – PolyGeo Jul 18 at 22:55
0

I wrote a tutorial exactly for this. As the Zonal Stats algorithm updates the existing layer instead of creating a new one, this algorithm is ideally run in a for-loop on one raster layer at a time.

Here's the relevant code snippet (you have to modify it slightly to work with your layer names). Assuming your raster layers start with name 'RASTER' and your vector layer is called 'VECTOR', the following should work

root = QgsProject.instance().layerTreeRoot()
for layer in root.children():
  if layer.name().startswith('RASTER'):
    prefix = layer.name()[-6:-4]
    params = {'INPUT_RASTER': layer.name(), 'RASTER_BAND': 1, 'INPUT_VECTOR': 'VECTOR', 'COLUMN_PREFIX': prefix+'_', 'STATS': 2}
    processing.run("qgis:zonalstatistics", params)

I tested it on 3.8 and it works. See the below tutorial for step by step instructions

http://www.qgistutorials.com/en/docs/3/processing_algorithms_pyqgis.html

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.