AnsweredAssumed Answered

Sort by shape token in Arcpy cursors?

Question asked by mmooreWPC on Oct 2, 2018
Latest reply on Oct 3, 2018 by bharold-esristaff

I have a script that uses the sql orderby parameter to sort my arcpy cursors by a user defined field or fields and deletes duplicates, but keeps the duplicate with the highest value. I'd like to be able to sort by geometry to identify/group features that are spatial duplicates and delete those that are duplicates (but keeping the duplicate with the highest value in another chosen field which is why I can't just use the Delete Identical tool).

 

I have tried several ways of doing this, but as I understand, shape tokens such as SHAPE@, SHAPE@WKT, etc. cannot be used in the sql clause. Is there another way to do this or another workaround? I also tried to add a field and fill with the SHAPE@WKT, but the update cursor did not fill the field.

 

Here is the code I've got that works for other fields, other than the geometry field:

 

import arcpy
from itertools import groupby
from operator import itemgetter

input_layer = arcpy.GetParameterAsText(0)
case_fields = arcpy.GetParameterAsText(1)
max_field = arcpy.GetParameterAsText(2)
case_fields = case_fields.split(";")
case_fields = [str(x) for x in case_fields]

sql_orderby = "ORDER BY {}, {} DESC".format(",".join(case_fields), max_field)

with arcpy.da.UpdateCursor(input_layer, "*", sql_clause=(None, sql_orderby)) as cursor:
    case_func = itemgetter(*(cursor.fields.index(fld) for fld in case_fields))
    for key, group in groupby(cursor, case_func):
        next(group)
        for extra in group:
        cursor.deleteRow()

Outcomes