0

I am very new to Python and have no idea about how to write a python loop to do selections for ArcGIS. I already finished writing selection codes with different conditions. Is there anyone helping me revise my codes with a python loop?

import arcpy
arcpy.env.workspace = "D:/STAR/STARproject.gdb"
arcpy.MakeFeatureLayer_management('wqi_Conshp_clip27171','wqi_Conshp_clip27171')

#Select level 1 gridcode<=14.3
selection1 = '"gridcode"<=14.3'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection1)

arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel1',[["Shape_Area","sum"]])
#summarize the selected features
arcpy.AddField_management('stats27171wqi_Conlevel1','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel1','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3') 
#Sum_Area27171 is a variable and already defined in the workspace

#select level 2 14.3<gridcode<=25.6

selection2 =  '"gridcode">14.3 AND "gridcode"<=28.6'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection2)

arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel2',[["Shape_Area","sum"]])

arcpy.AddField_management('stats27171wqi_Conlevel2','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel2','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3') 

#select level 3 28.6<gridcode<=42.9

selection3 =  '"gridcode">28.6 AND "gridcode"<=42.9'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection3)
arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel3',[["Shape_Area","sum"]])

arcpy.AddField_management('stats27171wqi_Conlevel3','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel3','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3') 

#select level 4 42.9<gridcode<=57.2

selection4 =  '"gridcode">42.9 AND "gridcode"<=57.2'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection4)


arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel4',[["Shape_Area","sum"]])

arcpy.AddField_management('stats27171wqi_Conlevel4','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel4','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')

#merge these results
arcpy.Merge_management(['stats27171wqi_Conlevel1','stats27171wqi_Conlevel2','stats27171wqi_Conlevel3',
                    'stats27171wqi_Conlevel4'],'stats27171wqi_ConMerge')

As you can see, there are four conditions above. Actually, I have another three similar conditions. I am wondering how to combine these selections together with a loop in python to make the work as simple as possible.

  • 1
    It looks like for each condition you are performing a selection, adding fields, and calculating fields. Because of this I'd create a function in which you pass the query and fieldname, and then loop through calls to this function. – smiller Apr 5 at 20:49
  • @smiller, thanks for your help. Writing a function is a kind of complex for me. Do you know where I can find similar examples for looping or functions? Appreciate it! – Zhenyu Apr 5 at 20:53
0

The above question is part of a script. The purpose of the script is to create a buffer and do selections based on the percentage of different values. Here is the updated version of my script and hope it is useful for other users.

import pandas as pd
import arcpy
arcpy.env.workspace = "D:/WQ.gdb"
arcpy.env.overwriteOutput = True #overwrite the exsiting files

selection1 =  '"gridcode"<=14.3'
selection2 =  '"gridcode">14.3 AND "gridcode"<=28.6'
selection3 =  '"gridcode">28.6 AND "gridcode"<=42.9'
selection4 =  '"gridcode">42.9 AND "gridcode"<=57.2'
selection5 =  '"gridcode">57.2 AND "gridcode"<=71.5'
selection6 =  '"gridcode">71.5 AND "gridcode"<=85.8'
selection7 =  '"gridcode">85.8 AND "gridcode"<=100'
#these are the selection conditions for 7 levels of WQI

selections = [selection1, selection2, selection3, selection4,
          selection5, selection6, selection7]

for point in random: #random is a list including all unique values of a field
    pointname = "n" + str(point)
    fieldname = 'ARC_'
    whereClause = """{0} = {1}""".format(arcpy.AddFieldDelimiters(pointlayer, fieldname),point)  
    arcpy.MakeFeatureLayer_management(pointlayer,pointlayer)  

    arcpy.SelectLayerByAttribute_management(pointlayer,'NEW_SELECTION',whereClause)

    print pointname

    buffername = pointname + "buffer25"
    #define the buffer's name
    arcpy.Buffer_analysis(pointname,buffername,"25 miles")
    #make a 5 miles buffer around the selected point
    print buffername

    bufferclip = scenairo + "25" + "clip" +pointname
    #define a clip name
    arcpy.Clip_analysis(scenairo,buffername,bufferclip)
    print bufferclip

    #######################################################################
    #calculate the area of the buffer
    list = []
    rows = arcpy.SearchCursor(bufferclip)
    SumArea = bufferclip + "Area"

    for row in rows:
        area = row.getValue("Shape_Area")
        list.append(area)
        SumArea = sum(list)
    print SumArea

    #######################################################################

    arcpy.MakeFeatureLayer_management(bufferclip,bufferclip)

    count = 0 #define a number for the name of selected name
    statisticstables = []
    selectionmerge = bufferclip + "_Merge" 

    for selection in selections:

        count = count + 1
        selectionname = bufferclip + "level" + str(count)
        #define the selection name such as level1 and level2
        statisticstables.append(selectionname)

        ratename = "rate" + str(point)
        arcpy.SelectLayerByAttribute_management(bufferclip,'NEW_SELECTION',selection)
        arcpy.Statistics_analysis(bufferclip,selectionname,[["Shape_Area","sum"]])

        ######checking if the selectionname is empty and then add a new row with zeros if empty
        fields = ['FREQUENCY','Sum_Shape_Area'] #do not set OBJECTID

        if int(arcpy.GetCount_management(selectionname).getOutput(0)) == 0:

            icur = arcpy.da.InsertCursor(selectionname,fields)
            icur.insertRow([0,0])
            del icur

        arcpy.AddField_management(selectionname,ratename,'DOUBLE') #add a new field
        arcpy.CalculateField_management(selectionname,ratename,'!SUM_Shape_Area!/{}'.format(SumArea),'PYTHON_9.3') 
        print selectionname

        arcpy.Merge_management(statisticstables, selectionmerge) #merge all level tables into one table

    pathname = "scenairo" + str(i)
    outpath = "D:\\STAR\\" + pathname
    outresult = outpath + "\\" + selectionmerge + ".xls"
    arcpy.TableToExcel_conversion(selectionmerge,outresult)
    print outresult

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.