[GIS] Iterate through features to use selection as input for ExtractByMask

arcpycursorextract-by-maskfeaturesiteration

I need to iterate through each of the features of a feature class successively to use each one as the mask to extract from a raster with the ExtractByMask tool. Basically I'm looking for the "Iterate Feature Selection" function from ModelBuilder for Python scripting.

If I understand correctly, using a search cursor will return only the row of values from the attribute table, not the feature shape itself.

Would iteratively creating a new shape with "Select_Analysis" be a feasible way to go about this instead?

I suppose creating a new shapefile for each feature would take quite long.

Is there another, more efficient way?

Best Answer

The SearchCursor will return geometries with the SHAPE@ token which can be used as extracting features etc.:

SHAPE@ —A geometry object for the feature.

import arcpy

feature_class = r'C:\test.gdb\polygon'

with arcpy.da.SearchCursor(feature_class,'SHAPE@') as cursor:
    for row in cursor:
        #do something with row[0]

You can of course also return field values and use for example to name the outputs. In that case use a list of tokens and fields:

with arcpy.da.SearchCursor(feature_class,['SHAPE@','field1']) as cursor:
    for row in cursor:
        #do something

row[0] will be the geometry and row[1] the value of field1