Tuesday, 14 April 2015

Creating queries to select by attribute with arcpy



I'm quite new with arcpy and I'm finding selecting by attribute a bit of a nightmare. There's a problem with my query on the script below [query = "\'Location\' = observer"], but I can't tell what it is. 'Location' is a field of the feature class I'm dealing with (fc_copy).


with arcpy.da.UpdateCursor(fc_copy,field_names) as cursor:   
for row in cursor:
observer = row[0]
arcpy.MakeFeatureLayer_management(fc_copy, 'fl_copy_OBS')
arcpy.MakeFeatureLayer_management(fc_copy, 'fl_copy_TAR')
query = "\'Location\' = observer"
arcpy.SelectLayerByAttribute_management('fl_copy_OBS', 'NEW_SELECTION', query)
arcpy.SelectLayerByAttribute_management('fl_copy_TAR', 'NEW_SELECTION', query, invert_where_clause = 'INVERT')


This is the error I get => Invalid expression Failed to execute (SelectLayerByAttribute).


Is there any documentation to learn the rules to follow to build queries for arcpy?



Answer



The expression format depends on the data type and value being queried:


Shapefile querying text field:


query = "\"Location\" = '{}'".format(observer)

Geodatabase feature class querying text field:


query = "Location = '{}'".format(observer)

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