AnsweredAssumed Answered

Iterate many raster and many shapefiles in python

Question asked by nmietkiewicz on Oct 18, 2014
Latest reply on Oct 30, 2014 by nmietkiewicz

Hi all,

 

I am trying to iterate zonal statistics on many rasters (+200) over many shapefiles (+30), and step through the shapefiles such that each output table will be calculated across all raster for one shapefile.  For instance, shapefile #1 processes all zonal statistics for all rasters and merges it to one table, then shapefile #2 does the same, and so on until all shapefiles have been processed.  Any help/advice would be greatly appreciated! Below is the code I am currently working with.

 

# Import system modules
import arcpy, sys, os, string, glob


# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")
# Overwrite pre-existing files
arcpy.env.overwriteOutput = True
#Get the raster datasets in the input workspace and loop through them from the start


def zonal_climate_fire():
    for ws in listWS:
        arcpy.env.workspace = ws
        rasterlist = arcpy.ListRasters()
        shplist = arcpy.ListFeatureClasses()
        for k in rasterlist:
            for i in shplist:
                out_tbl = tbl + "\\" + k + "_ZStats"
                print '==============================================='
                print 'Zonal Statistics based on fire occurence : ' + k[6:-3]
                print '......'
                # Preform zonal statistics on the polygon file within the variable 'znlyr'
                z = arcpy.gp.ZonalStatisticsAsTable_sa(i, InZnValFld, k, out_tbl, "DATA", "MIN_MAX_MEAN")
                # Create a new field to add the filename information
                arcpy.AddField_management(z, fieldname1, "DOUBLE")
                # Create a new field to add the filename information
                arcpy.AddField_management(z, fieldname2, "DOUBLE")
                # Add the Year value from the filename to the new field
                arcpy.CalculateField_management(z, fieldname1,k[6:-3])
                # Add the Year value from the filename to the new field
                arcpy.CalculateField_management(z, fieldname2,k[11:])
                arcpy.Append_management(z, Template, "","","")

#--------------------Main to set variables--------------------------------------------------
znshp = "C:\\tmp\\znshp\\"
grd = "C:\\tmp\\grd\\"
tbl = "C:\\tmp\\tbl\\"
InZnValFld = "ID"
fieldname1= "Year"
fieldname2= "Month"
Template = "C:\\tmp\\tbl\\Template.dbf"


#Creates a list of multiple workspaces
listWS = [grd, znshp]

zonal_climate_fire ()

 

Thank you all in advance,

Nate

Outcomes