Monday 27 March 2017

python - Using for loop to execute query in ArcPy?


I'm trying to provide the breakdown of fire detection for an area by sorting of confidence levels. The dataset has 12 files (one for each month in a year) with fire records which all have a column called "confidence" with a value between 0 and 100. I have to use a for loop to query the files by 3 different confidence levels. Group 1: >85% confidence Group 2: 60-85% confidence Group 3: <60% confidence


I HAVE TO USE a for loop to execute this. Any ideas? I started by appending all the files into one list. I'm told that I could use lists to set up lower and upper ranges and SelectLayerByAttribute_management, and use that in a loop, but don't know how to do that.


This is my final code that works. I decided to merge the files together into one big file.


arcpy.env.workspace = "***********/data/" 

list1 = [];

for month in range(1,13):

inf = "2007" + str(month).zfill(2)+ "_rfe"
arcpy.DefineProjection_management(newpath + inf + ".shp", 4326)
list1.append(newpath + inf + ".shp")

out1 = "big2007" + "_rfe" + ".shp"
layer1 = "layer1" + ".shp"
arcpy.Merge_management(list1,out1)
arcpy.MakeFeatureLayer_management(out1, layer1)

lower = [0, 60, 86]

upper = [60, 86, 101]

for i in range(len(lower)):
arcpy.SelectLayerByAttribute_management(layer1, "NEW_SELECTION", """ "CONF" >= {} and "CONF" < {}""".format(lower[i],upper[i]))
result = arcpy.GetCount_management(layer1).getOutput(0)
result = int(round(result))

Answer



I assume that your files are in the same directory. I don't know why you Have to use a for loop, as it adds unnecessary complexity, but here is an example where you can create two lists (one with the lower ranges and the second with the upper ranges), that you insert into the where clause when creating the layer (you can also create a single layer without where clause, and use the same where clause to select by attribute within this layer)


minvals = [85, 60 , -1  ]
maxvals = [100, 85, 60]


fcs = arcpy.ListFeatureClasses()
for fc in fcs:
for i in range(len(minvals)):
arcpy.MakeFeatureLayer(fc, fc[:-4]+str(i+1), """ "confidence_field_name" > {} And "confidence_field_name" <= {}""".format(minvals[i],maxvals[i]) )

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...