"If" Statement and Loop - ArcPy for ArcGIS Pro

2968
24
01-18-2018 11:26 AM
Business_IntelligenceSoftware
Occasional Contributor

I have this code that performs a Summarize Within on all company stores for every month of the year. However, not all the stores were open in some of the early months so I need to write some code that will identify that the "USER_PatientVisits" is equal to zero and then skip that store and move on to the next. I'm thinking this can be accomplished using an "If" statement and probably a loop; however, I'm not sure what exactly to write and how to bring it all together.

Here is the top portion of my code for January and February; the full code continues on through December:

import arcpy
import sys
import os
import datetime

#now = datetime.datetime.now()

arcpy.env.overwriteOutput = True

#Set the workspace
from arcpy import env
env.workspace = r"C:\arcGIS_Shared\Python\CenterHeatMaps.gdb"

#Declare variables
fc = 'Open_Store_Centers'
fields = ['USER_market_id','USER_Store_ID','USER_Store_Center_Name']
fieldname = 'USER_market_id'

#Define WHERE clause statement
whereclause = """{} = 2000""".format(arcpy.AddFieldDelimiters(fc, fieldname))

#Cursor to create list of centers to loop through
cursor = arcpy.da.SearchCursor(in_table = fc, field_names = fields, where_clause=whereclause, sql_clause=(None, 'ORDER BY USER_market_id, USER_Store_ID'))

#Loop to run SummarizeWithin by center
for row in (cursor):
    #  Set variables for SummarizeWithin
    #  Specify type of summarization, either Blocks or ZIPS, as part of the polys argument
    polys = "Market{0}".format(row[0])+"Blocks"
    points = "Jan_NWPatientVisits{0}".format(row[0])+"{0}".format(row[2])
    outFeatureClass = "Jan_NWSumWithin{0}".format(row[0])+"{0}".format(row[2])
    keepAll = 'ONLY_INTERSECTING'
    sumFields = [['USER_VisitCount', 'Sum']]
    addShapeSum = 'ADD_SHAPE_SUM'

    arcpy.SummarizeWithin_analysis(polys, points, outFeatureClass, keepAll, sumFields, addShapeSum, '')
    
    #Print Results
    print(row[2])
#    print("SumWithin Elapsed Time:" + SumWithinruntime)
#    count = arcpy.GetMessageCount()
#    print (arcpy.GetMessage(count-2))
    print (arcpy.GetMessages())
    
    
    #Declare variables
fc = 'Open_Store_Centers'
fields = ['USER_market_id','USER_Store_ID','USER_Store_Center_Name']
fieldname = 'USER_market_id'

#Define WHERE clause statement
whereclause = """{} = 2000""".format(arcpy.AddFieldDelimiters(fc, fieldname))

#Cursor to create list of centers to loop through
cursor = arcpy.da.SearchCursor(in_table = fc, field_names = fields, where_clause=whereclause, sql_clause=(None, 'ORDER BY USER_market_id, USER_Store_ID'))

#Loop to run SummarizeWithin by center
for row in (cursor):
    #  Set variables for SummarizeWithin
    #  Specify type of summarization, either Blocks or ZIPS, as part of the polys argument
    polys = "Market{0}".format(row[0])+"Blocks"
    points = "Feb_NWPatientVisits{0}".format(row[0])+"{0}".format(row[2])
    outFeatureClass = "Feb_NWSumWithin{0}".format(row[0])+"{0}".format(row[2])
    keepAll = 'ONLY_INTERSECTING'
    sumFields = [['USER_VisitCount', 'Sum']]
    addShapeSum = 'ADD_SHAPE_SUM'

    arcpy.SummarizeWithin_analysis(polys, points, outFeatureClass, keepAll, sumFields, addShapeSum, '')
    
    #Print Results
    print(row[2])
#    print("SumWithin Elapsed Time:" + SumWithinruntime)
#    count = arcpy.GetMessageCount()
#    print (arcpy.GetMessage(count-2))
    print (arcpy.GetMessages())‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
Tags (2)
0 Kudos
24 Replies
DanPatterson_Retired
MVP Esteemed Contributor

Code formatting please  it is unreadable in its current state.  Try not to edit code once it is pasted in either, that seems to be what happened.  Edit in the source, then paste

Business_IntelligenceSoftware
Occasional Contributor

Sorry about that. I don't know why it was in that format

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

Use the Python option within the syntax highlighter to get line numbers.

After this line

points = "Feb_NWPatientVisits{0}".format(row[0])+"{0}".format(row[2])

if points > 0:
    # then indent all your other lines
    # to continue the processing
    # just guessing since there are no line numbers 
    # and portions of the code seem to be duplicated
0 Kudos
XanderBakker
Esri Esteemed Contributor

Also when you feel that you are repeating code (like you now have a big block for Jan and another for Feb) it is time to use a loop. For instance have a list of the month prefixes that you want to use like months = ['Jan', 'Feb', ..., 'Dec'] and loop through the months. Something like this (ignoring any other changes that might be required in the code):

import arcpy
import sys
import os
import datetime

#now = datetime.datetime.now()
arcpy.env.overwriteOutput = True

#Set the workspace
from arcpy import env
env.workspace = r"C:\arcGIS_Shared\Python\CenterHeatMaps.gdb"

#Declare variables
fc = 'Open_Store_Centers'
fields = ['USER_market_id','USER_Store_ID','USER_Store_Center_Name']
fieldname = 'USER_market_id'

#Define WHERE clause statement
whereclause = "{0} = 2000".format(arcpy.AddFieldDelimiters(fc, fieldname))
sqlclause = (None, 'ORDER BY USER_market_id, USER_Store_ID')

# loop through months
months = ['Jan', 'Feb', 'Mar'] # add all the months
for month in months:
    #Cursor to create list of centers to loop through
    with arcpy.da.SearchCursor(in_table=fc, field_names=fields,
                               where_clause=whereclause, sql_clause=sqlclause) as cursor:

        #Loop to run SummarizeWithin by center
        for row in cursor:
            #  Set variables for SummarizeWithin
            #  Specify type of summarization, either Blocks or ZIPS, as part of the polys argument
            polys = "Market{0}".format(row[0])+"Blocks"
            points = "{2}_NWPatientVisits{0}{1}".format(row[0], row[2], month)
            outFeatureClass = "{2}_NWSumWithin{0}{1}".format(row[0], row[2], month)
            keepAll = 'ONLY_INTERSECTING'
            sumFields = [['USER_VisitCount', 'Sum']]
            addShapeSum = 'ADD_SHAPE_SUM'

            arcpy.SummarizeWithin_analysis(polys, points, outFeatureClass, keepAll, sumFields, addShapeSum, '')

            #Print Results
            print(row[2])
        #    print("SumWithin Elapsed Time:" + SumWithinruntime)
        #    count = arcpy.GetMessageCount()
        #    print (arcpy.GetMessage(count-2))
            print (arcpy.GetMessages())
Business_IntelligenceSoftware
Occasional Contributor

Yes the code is duplicated for each month. Unfortunately, "if points > 0:" gives me the following error.

TypeError: unorderable types: str() > int()

 

I then tried adding " " around the zero to change it from an integer to a string, which allowed it to run, but it did not exclude the stores with zero visits

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

if points is a string then you need  

if int(points) > 0:

Business_IntelligenceSoftware
Occasional Contributor

Ok I think we are close. I'm now getting the following error.

ValueError: invalid literal for int() with base 10: 'Apr_CTPatientVisits4000Avon'

I think this is because technically the attribute table for 'Apr_CTPatientVisits4000Avon' is blank and does not contain zero. 

Should it be "Null" instead?

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

and did you indent the code as well?

xander_bakker‌ could you try the indentation suggestion on your code to save a copy paste to show what I mean

0 Kudos
Business_IntelligenceSoftware
Occasional Contributor

Here is a little excerpt

polys = "Market{0}".format(row[0])+"Blocks"
    points = "May2_CTPatientVisits{0}".format(row[0])+"{0}".format(row[2])
    if int(points) > 0:
        outFeatureClass = "May_CTSumWithin{0}".format(row[0])+"{0}".format(row[2])
        keepAll = 'ONLY_INTERSECTING'
        sumFields = [['USER_VisitCount', 'Sum']]
        addShapeSum = 'ADD_SHAPE_SUM'
0 Kudos