2

The ArcGIS documentation for the Data Access Search Cursor states:

The records returned by SearchCursor can be constrained to match attribute criteria or spatial criteria.

But I can't see any example of how to specify spatial criteria when calling the search cursor. For this example I have a geometry and wish to constrain the results of the search cursor to only features which both intersect that geometry and meet other attribute criteria. e.g.

with arcpy.da.SearchCursor(fc,field_list,
                          "Admin_Code is null and shape intersects admin_area_geometry") 

I understand that I could perform a search cursor with the attribute query and then use the geometry intersects method but this would be slow to have to loop through each feature.

How can I specify both the spatial criteria when creating a search cursor?

4
  • Can you expand more what you mean by "intersect that geometry". Are you wanting to intersect two layers or one layer with itself?
    – artwork21
    Commented Jul 25, 2015 at 11:59
  • It's two layers - I want to base an ID/admin_code on the intersecting polygon, but only need to identify those intersecting the input admin area where the admin_code is null - hence my reluctance to loop through all features.
    – kes
    Commented Jul 25, 2015 at 12:13
  • 2
    I wonder if the documentation is simply alluding to using SelectLayerByLocation before arcpy.da.SearchCursor.
    – PolyGeo
    Commented Jul 25, 2015 at 12:56
  • Thanks @PolyGeo, that worked - I used select by location to give a combination of spatial + attribute condition. Hadn't realised the cursors now accept feature layers which I spotted in another of your answers.
    – kes
    Commented Jul 25, 2015 at 15:43

1 Answer 1

1

I would suggest using a where clause to lessen the impact of pulling out geometry info that way you are not iterating through the entire table:

import arcpy

fc = 'c:/base/data.gdb/roads'
class_field = 'Road Class'
name_field = 'Name'

# Create an expression with proper delimiters
expression = arcpy.AddFieldDelimiters(fc, name_field) + ' = 2'

# Create a search cursor using an SQL expression
with arcpy.da.SearchCursor(fc, [class_field, name_field, SHAPE@],
                           where_clause=expression) as cursor:
    for row in cursor:
        # continue with logic
1
  • Thanks - that's where I'm at but I'd also like to limit the search cursor with a spatial condition, as hinted at in the ESRI docs.. frustratingly this would be easy in SQL with ST_INTERSECTS but I'm finding it difficult to replicate in ArcPy..
    – kes
    Commented Jul 25, 2015 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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