I am trying to run a Python script that loops through all fields in my input feature attribute table. I have searched extensively and tried to use arcpy.ListField to work but it seems all people got stuck on the same issue: we cannot get the columns we are trying to loop to work as input field.
Here is my script:
import arcpy
arcpy.env.workspace = "C:\Users\jacobyan\Desktop\JACOB"
fieldList = arcpy.ListFields("BG_SAR1.shp")
try:
#Call all fields in the list
for field in fieldList:
outputname = str(field.name) + ".shp"
print outputname
arcpy.ClustersOutliers_stats("BG_SAR1.shp", "field", outputname, "GET_SPATIAL_WEIGHTS_FROM_FILE","EUCLIDEAN_DISTANCE", "ROW", "#", "SpatialWeights.swm","NO_FDR")
except:
print arcpy.GetMessages()
The result I got is:
FID.shp Executing: ClustersOutliers C:\Users\jacobyan\Desktop\JACOB\BG_SAR1.shp field C:\Users\jacobyan\Desktop\JACOB\FID.shp GET_SPATIAL_WEIGHTS_FROM_FILE EUCLIDEAN_DISTANCE ROW # C:\Users\jacobyan\Desktop\JACOB\SpatialWeights.swm NO_FDR Start Time: Wed Jul 29 14:45:56 2015 Failed to execute. Parameters are not valid. ERROR 000728: Field field does not exist within table Failed to execute (ClustersOutliers). Failed at Wed Jul 29 14:45:56 2015 (Elapsed Time: 0.03 seconds)
I adjust "field" to "field.name" and try to replace it with FieldList[count], but none of those worked.
Here are two related posts I have looked at: Iterating through columns in table using ModelBuilder?
1 Answer 1
How you have it now, you're going to run the tool using the FID and SHAPE fields. You need to limit your fields to the ones you actually want to use as input. Also, when you use field
as the input in the tool, it's actually the field object. You need to use field.name
instead.
import arcpy
#should use two backslashes in file path
arcpy.env.workspace = "C:\\Users\\jacobyan\\Desktop\\JACOB"
fieldList = arcpy.ListFields("BG_SAR1.shp")
for field in fieldList:
try:
#this will remove FID and SHAPE
if not field.required:
field_name = str(field.name)
output_name = field_name + ".shp"
arcpy.ClustersOutliers_stats("BG_SAR1.shp", field_name, output_name, "GET_SPATIAL_WEIGHTS_FROM_FILE","EUCLIDEAN_DISTANCE", "ROW", "#", "SpatialWeights.swm","NO_FDR")
except:
print arcpy.GetMessages()
Another way is just to replace:
fieldList = arcpy.ListFields("BG_SAR1.shp")
with:
fieldList = ["YourField1", "YourField2", "YourField3"]
and replace "YourField" with whatever fields you want to use as input.
-
Thanks for your incisive comments! You hit the main issues with my old script.Jacob Yan– Jacob Yan2015年07月29日 19:49:28 +00:00Commented Jul 29, 2015 at 19:49
"field"
withfield.name
. Also, in your question, it would be better if you could format the code by adding four spaces to the beginning of each line with code in it.