[GIS] Batch Zonal Statistics as table

arcgis-10.2arcpyerror-999999spatial-analystzonal statistics

I want to calculate zonal statistics as table for multiple rasters, but can't figure out how. What I am trying is:

import arcpy, os
arcpy.env.workspace=r'F:\Sheyenne\Atmospherically Corrected Landsat\Indices\Main\NDWI\main_master'
#zones to calculate stats on
inpoly=r'F:\Sheyenne\SNG_sections.shp'
#where to save output files
destination_path=r'F:\Sheyenne\Atmospherically Corrected Landsat\Indices\Main\NDWI\zonal_stats'
 #list of rasters to calculate statistics on
rasters = arcpy.ListRasters("*water_.tif*")
#start loop
for raster in rasters:
    destination_path = os.path.join(destination_path, raster + ".dbf")
    arcpy.gp.ZonalStatisticsAsTable_sa(inpoly, "OBJECTID",raster, destination_path,"DATA","ALL")

The error returned is :

Traceback (most recent call last):

  File "<ipython-input-10-9522776a92dd>", line 1, in <module>
    runfile('F:/python codes/zonal_stats.py', wdir='F:/python codes')

  File "C:\Users\spotter\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)

  File "C:\Users\spotter\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "F:/python codes/zonal_stats.py", line 21, in <module>
    arcpy.gp.ZonalStatisticsAsTable_sa(inpoly, "OBJECTID", raster, destination_raster,"DATA","ALL")

  File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\geoprocessing\_base.py", line 498, in <lambda>
    return lambda *args: val(*gp_fixargs(args, True))

ExecuteError: ERROR 999999: Error executing function.
Create output table failed
Failed to execute (ZonalStatisticsAsTable).

Best Answer

The fourth parameter to ZonalStatisticsAsTable should be the output name - since you've put "DATA" there (which should be parameter 5), you're likely getting no output. You'll need to put your destination_path variable in that location.

But I'll also caution you that, as written, destination_path is going to keep growing since you're appending to it in each round of your loop. Try assigning to a new variable. Something like

for raster in rasters:
    destination_raster = os.path.join(destination_path, raster + ".dbf")
    arcpy.gp.ZonalStatisticsAsTable_sa(inpoly, "OBJECTID", raster,destination_raster,"DATA","ALL")

That style should preserve destination_path for each iteration and let you reuse a variable to provide to the Zonal Stats function call.

Related Question