Friday, 12 January 2018

arcpy - Python Script Zonal Stats as Table Loop Question



I'm trying to write a small script loop script which retrieves rasters from each folder, performs zonal statistics using watershed polygons and saves it as a table. I've written similar loop scripts, but this seems to be confusing me. Here's what I have so far:


import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = "F:/lu_crop_rast"
arcpy.env.overwriteoutput = 1

watershedFeat = "F:/watersheds.shp"
outDir = "F:/lu_crop_rast/tables/"


for raster in arcpy.ListRasters():
outTable = outDir + raster + "_TBL.dbf"
arcpy.sa.ZonalStatisticsAsTable(watershedFeat,"Name",raster,outTable,"NODATA","MEAN")

This is the error I'm getting:


Runtime error  Traceback (most recent call last):   
File "", line 15, in File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\sa\Functions.py", line 6232, in ZonalStatisticsAsTable statistics_type)
File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\sa\Utils.py", line 53, in swapper result = wrapper(*args, **kwargs) File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\sa\Functions.py", line 6224, in Wrapper statistics_type)
File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\geoprocessing\_base.py", line 504, in return lambda *args: val(*gp_fixargs(args, True)) ExecuteError: ERROR 999999: Error executing function. Create output table failed Failed to execute (ZonalStatisticsAsTable).


I've checked and my rasters and shapefile aren't corrupt. I've looked at this thread as well and made the following changes:


arcpy.gp.ZonalStatisticsAsTable_sa(watershedFeat,"Name",raster,outTable,"NODATA","MEAN")

But so far nothing seems to work.



Answer



You need to dedent and modify your naming (thanks Tom). Try this:


import arcpy, os
arcpy.env.overwriteOutput = True

-



for raster in arcpy.ListRasters():
raster_name = os.path.basename(raster).rstrip(os.path.splitext(raster)[1])
outTable = outDir + raster_name + "_TBL.dbf"
arcpy.gp.ZonalStatisticsAsTable(watershedFeat,"Name",raster,outTable,"NODATA","MEAN")

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...