I have a Python Toolbox and want to use the zonal statistics as table function on user-provided polygon shapefiles/feature classes that may or may not have multiple parts.
In the code, I add a new field to the user-provided polygon and create the zones (code below is abbreviated with only pertinent parts):
polygon = parameters.value arcpy.AddField_management(polygon, "Zone", "TEXT", "", "", 15)
EDIT 1: (code immediately below)
d=arcpy.Describe(polygon) if d.dataType == 'FeatureLayer': polygon = d.featureClass.catalogPath
Then using field calculator, I create sequential zone numbers:
expression = "autoIncrement(!FID!)" codeblock = """def autoIncrement(fid): fid = int(fid) fid += 1 return "Polygon " + str(fid)""" arcpy.CalculateField_management(polygon, "Zone", expression, "PYTHON", codeblock)
When I try the tool, the CalculateField_management function stalls and I receive "Error 000728: Field "Zone" does not exist within table". However, opening up the shapefile used to test the tool does reveal that a new field called "Zone", string datatype and length of 15 has been created.
When I refresh the Python toolbox and rerun the tool, this time it runs correctly populating the rows ("Polygon 1", "Polygon 2", ...) and the ZonalStatisticsAsTable function is able to run.
I found a previous post on this issue: Why am I getting an ERROR 000728: Field *fieldname* does not exist within table even though field exists?
(1) Instead of using arcpy.CalculateField_management, I tried using an update cursor.
arcpy.AddField_management(polygon, "Zone", "TEXT", "", "", 15) start = 1 cursor = arcpy.da.UpdateCursor(polygon, "Zone") for row in cursor: row = "Polygon " + str(start) start = start + 1 cursor.updateRow(row) del row, cursor arcpy.sa.ZonalStatisticsAsTable(polygon, "Zone", ...) [code goes on]
Instead of the previous error, the code stalls on the ZonalStatisticsAsTable function instead and I receive "Error 001000: Field "Zone" does not exist". As before, checking the shapefile's attribute table reveals that the "Zone" field exists as it should after arcpy.AddField_management function.
(2) Use "FID" as zones to avoid having to use arcpy.AddField_management and arcpy.sa.ZonalStatisticsAsTable in succession.
Tool does now run without either errors, yet summary statistics are incorrect. Basically it looks like values of "MIN", "MAX", and "MEAN" have been shifted over, so this doesn't look like a viable option.
My thoughts: Is there some kind of lock preventing the code from running top to bottom? Issue occurs after I add the new field and then want to do something to that field. It's weird that I need to rerun the code twice in order to not receive errors. Since I hope to have this tool available for other users, this isn't acceptable.