Thursday, 7 June 2018

Setting up where_clause to select counties one at a time from feature class using ArcPy?


I need to select a single county at the time from the "counties" feature class. I am using a make feature layer with a where clause.


How do I set up the where_clause to select each of the counties in the row? The field list to be used by the update cursor is "COUNTY". In this list are all the 64 counties names. Here is what I have so far:


# where clause
COname = ??????
where_clause = "COUNTY = '" + COname + "'"

print where_clause
arcpy.MakeFeatureLayer_management (CountyPath, "county_lyr", where_clause)

Answer



This sounds like you want to get a list of what's there first and then iterate each one.. take for example:


AllCounties = [] # blank list
with arcpy.da.SearchCursor(CountyPath,'COUNTY') as SCur:
for SRow in SCur: # go through each feature one by one
if SRow[0] not in AllCounties: # check it's not already in the list
AllCounties.append(SRow[0])


for ThisCounty in AllCounties:
where_clause = "COUNTY = '" + ThisCounty + "'"
#... do the rest of what you need to do here

On the surface all looks good, but you have to consider case sensitivity. File geodatabases and shapefiles are case sensitive so I would suggest something like this:


AllCounties = [] # blank list
with arcpy.da.SearchCursor(CountyPath,'COUNTY') as SCur:
for SRow in SCur: # go through each feature one by one
if SRow[0].upper() not in AllCounties: # check it's not already in the list
AllCounties.append(SRow[0].upper())


for ThisCounty in AllCounties:
where_clause = "upper(COUNTY) = '" + ThisCounty + "'"
#... do the rest of what you need to do here

To do all your comparisons in upper case. Both SQL and python have upper methods but they are used differently; in python you would uppercase StringVar by typing StringVar.upper() but in SQL you would perform an uppercase comparison of field StringField by typing upper(StringField). In both languages there is the option of upper and lower but try to stick to the same case, it would be frustrating to find the uppercase matching string in a list of lowercase strings.


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