"If" Statement and Loop - ArcPy for ArcGIS Pro

4737
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 Emeritus

line 4

if row[0] is not None:  # because row[0] is the point count I presume and it is either None, <null> or 0

if row[0] returns 0 then it goes back to 

if row[0] <> 0:  # then do something

XanderBakker
Esri Esteemed Contributor

I'm confused... how is points ever going to be None when it will always have text in it?

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

What do you want to validate? Maybe using different variable name would avoid confusion. Using "points" for a text is not part of best practices.

Also, try no to combine "+" and ".format()" to create a string. Just use format to make it more readable (like I suggested before in the code I posted) and make the month variable in order to avoid repeating blocks of code:

my_text_not_points = "{0}_CTPatientVisits{1}{2}".format(month, row[0], row[2])
0 Kudos
Business_IntelligenceSoftware
Occasional Contributor

Okay maybe I need to take a step back and give some more details. 

So I have multiple steps of code each in its own document. Step 1 geocodes a table of all Patient Visits. Step 2 then takes the geocoded results and creates a feature class for each Store's visits for every month for 2017. Then Step 3 is what we have been working on with the Summarize Within. So maybe I should have led off with Step 2 instead of Step 3.

Here is the code for Steps 1 and 2.

Step 1

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

# Set local variables:
address_table = "PatientVisits"
address_locator = "C:/2016 US Data/ESRI_BA_2016_US_Data_Update/USA_LocalComposite"
address_fields = "Address AddressLine1;City City;State State;ZIP_Code ZIP"
geocode_result = "PatientVisitsGeocoded"

arcpy.GeocodeAddresses_geocoding(address_table, address_locator, address_fields, geocode_result, 'STATIC')

Step 2

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

#Define WHERE clause statement
whereclause = """{} = 4000""".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 through each row established in cursor
for row in (cursor):
    # Set local variables for FeatureClasstoFeatureClass
    inFeatures = "PatientVisitsGeocoded"
    outLocation = r"C:\arcGIS_Shared\Python\CenterHeatMaps.gdb"
    outFeatureClass = "May_CTPatientVisits{0}".format(row[0])+"{0}".format(row[2])
    delimitedfield = arcpy.AddFieldDelimiters(arcpy.env.workspace,"USER_CenterID")
    expression = delimitedfield + "= {0}".format(row[1]) + "AND USER_DOSYear = 2017 AND USER_DOSMonth = 'May'"
#   Where clause for Financial Class 
# + "AND USER_OrigFinClass = 'BCBS'"

    # Execute FeatureClassToFeatureClass
    arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, outFeatureClass, expression)

    #Print Results
    print(row[2])
    count = arcpy.GetMessageCount()
    print (arcpy.GetMessage(count-1))

Step 2 repeats the same code for every month so that is obviously something I need to change into a loop

I hope this helps clear stuff up, because I think we are all a little confused 

0 Kudos
DanPatterson_Retired
MVP Emeritus

And my final contribution will be regarding what 'row[0]' is

If it is zero (0), None, <null>, nadda... do you want to continue or not?

 row0 = None  # pretend this is row[0]

"May_CTPatientVisits{0}".format(row0)  # ditto

'May_CTPatientVisitsNone'  # ---- is this what you want? or do you want to bail
0 Kudos
Business_IntelligenceSoftware
Occasional Contributor

Unfortunately I think I will have to put this project on the back burner for now. Thank you everyone for your help. Sorry for any confusion or inconvenience. If I figure out this problem I will post the solution. Thanks 

0 Kudos