Select to view content in your preferred language

Zonal Statistic with multiple shapefiles only works on first file

507
1
01-27-2022 10:30 AM
MatthewWatson3
New Contributor

I am attempting to calculate zonal statistics on a single raster for multiple shapefiles. When I load all the shapefiles into the contents pane the code runs (tested on 5 files), but I have thousands of shapefiles I need to conduct this calculation and cannot load them all into the contents pane. When I dont load the files to the contents pane only the zonal stat for the first file is calculated, after that an error is returned:

ExecuteError                              Traceback (most recent call last)
In  [10]:
Line 23:    outzone = ZonalStatistics(shape[i], "presence", Raster("C:pathway to file/.tif"), "MAXIMUM", "NODATA")

File c:\program files\arcgis\pro\Resources\arcpy\arcpy\sa\Functions.py, in ZonalStatistics:
Line 6530:  process_as_multidimensional)

File c:\program files\arcgis\pro\Resources\arcpy\arcpy\sa\Utils.py, in swapper:
Line 53:    result = wrapper(*args, **kwargs)

File c:\program files\arcgis\pro\Resources\arcpy\arcpy\sa\Functions.py, in Wrapper:
Line 6522:  process_as_multidimensional)

File c:\program files\arcgis\pro\Resources\arcpy\arcpy\geoprocessing\_base.py, in <lambda>:
Line 511:   return lambda *args: val(*gp_fixargs(args, True))

ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000865: Input raster or feature zone data: Abrawayaomys_chebezi.shp does not exist.
WARNING 001000: Zone field: Field presence does not exist
Failed to execute (ZonalStatistics).

The full code is listed below:

import arcpy
from arcpy import env
from arcpy.sa import *

arcpy.CheckOutExtension("Spatial")


indir = "C:/pathway to folder"
outdir = "C:/pathway to output/"


env.workspace = indir

shape = arcpy.ListFiles("*.shp")
i = 0
while i < len(shape):
outzone = ZonalStatistics(shape[i], "presence", Raster("pathway to raster"), "MAXIMUM", "NODATA")
outzone.save(outdir+shape[i]+"_Jan_Max.tif")
del outzone
i += 1
print ("Sampling iteration #" + str(i))
print ("Complete")



 the pathways were changed just for this question.

 

is there any suggestions for how to avoid this error?

0 Kudos
1 Reply
DanPatterson
MVP Esteemed Contributor

Code formatting ... the Community Version - Esri Community

to assist with proper indentation checks and to provide line numbers for reference

In any event, throw in some print statements to confirm that the concatenation process results in a correct filename.

outdir = "C:/pathway to output/"
shape = "a.shp"  # -- I assume here that the path is removed
outdir+shape+"_Jan_Max.tif"  # -- wrong because *.shp not removed
'C:/pathway to output/a.shp_Jan_Max.tif'

outdir+shape[:-4]+"_Jan_Max.tif" # -- right if file extension is present
'C:/pathway to output/a_Jan_Max.tif'

so make sure that the shapefile is stripped of path and file extension first.


... sort of retired...
0 Kudos