2

I got this Python script from this previous post. I've edited it for my project but nothing happens when I execute it. I downloaded the zonal statistics plugin, and usually when I run it, it adds a new field to the shapefile with the statistics I need, for example minimum. Since I need to do it multiple times, I was hoping to use the script. I tried the batch execute, but for GDAL it doesn't allow you to select one statistic, and Saga always gives an error somewhere.

Here's the script I use:

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('D:/all_structures_tez.shp', 'zonepolygons', "ogr") 

# specify raster filename
rasterFilePath = 'D:/slow.tif'

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

QGIS ver 2.18.3

  • The code runs fine for me. When you open all_structures_tez after running it, there are no added columns, right? – jbukoski Apr 15 '17 at 16:21
  • hi! exactly..after running the script, i don't see any added columns. I also saved the script and execute it from the toolbox, but nothing. – Jeff Legitime Apr 15 '17 at 16:34
  • Do you have the shp loaded in QGIS and are just checking the attribute table after running the script? I have to reload the shp to Q after running the code in order to see the attributes (i.e., it doesn't update the layer immediately). – jbukoski Apr 15 '17 at 17:00
  • @JeffLegitime try also to set the layer in edit mode before running the script... – mgri Apr 15 '17 at 17:22
  • 1
    @mgri thank you! After putting it in edit mode it worked! Please put your comment as answer to give you credit. – Jeff Legitime Apr 15 '17 at 18:29
4

I performed a quick test and it seems that you need to turn on the edit mode for obtaining the desired result.

If you want to use Python for this, try to use the following code:

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

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.