Cursor Performance against Layer Selections

126
1
Jump to solution
2 weeks ago
tcrammond
New Contributor

I've been passing the results of selections against layers directly to the arcpy.da.UpdateCursor, and noticed that the performance is terrible. I love the convenience of not deriving some whacky SQL to tell the cursor exactly what I want to update...but at this point, the juice ain't worth the squeeze.

Any tips on making this work? The process is usually something like

selected_stuff = arcpy.GetParameter('selection')  # feature layer input with a selection applied

metrics = {id: metric for id, metric in results}  # parse through some table of results to get the stuff I wan to update

with arcpy.da.UpdateCursor(
        selected_stuff,
        field_names=['id', 'metric'],
) as i_cursor:
    for row in i_cursor:
        metric = metrics.get(row[0])

        if metric and metric != row[1]:

            row[1] = metric
            i_cursor.updateRow(row)
0 Kudos
1 Solution

Accepted Solutions
AlfredBaldenweck
MVP Regular Contributor

I haven't run into this issue myself, but you could try something like:

 

 

selected_stuff = arcpy.GetParameter('selection')  # feature layer input with a selection applied

actualFC = selected_stuff.dataSource
selSet = selected_stuff.getSelectionSet() # get set of OIDs of selected feature

sql = f"OBJECTID IN ({', '.join([str(i) for i in selSet])})"

metrics = {id: metric for id, metric in results}  # parse through some table of results to get the stuff I want to update

with arcpy.da.UpdateCursor(
        actualFC,
        field_names=['id', 'metric'],
        where_clause = sql
) as i_cursor:
    for row in i_cursor:
        metric = metrics.get(row[0])

        if metric and metric != row[1]:

            row[1] = metric
            i_cursor.updateRow(row)

 

Basically, run the cursor on the actual table based on what you have selected, rather than on the layer.

View solution in original post

0 Kudos
1 Reply
AlfredBaldenweck
MVP Regular Contributor

I haven't run into this issue myself, but you could try something like:

 

 

selected_stuff = arcpy.GetParameter('selection')  # feature layer input with a selection applied

actualFC = selected_stuff.dataSource
selSet = selected_stuff.getSelectionSet() # get set of OIDs of selected feature

sql = f"OBJECTID IN ({', '.join([str(i) for i in selSet])})"

metrics = {id: metric for id, metric in results}  # parse through some table of results to get the stuff I want to update

with arcpy.da.UpdateCursor(
        actualFC,
        field_names=['id', 'metric'],
        where_clause = sql
) as i_cursor:
    for row in i_cursor:
        metric = metrics.get(row[0])

        if metric and metric != row[1]:

            row[1] = metric
            i_cursor.updateRow(row)

 

Basically, run the cursor on the actual table based on what you have selected, rather than on the layer.
0 Kudos