I have a feature class and I need to renumber from 1 and increase by 1 for a group of features. To do that, I need to define these groups (based on atributes of a field) and for each group make an update cursor. My problem is that in my code, just the first group of features are updated and the others not. Where is my mistake?

This is what I have today

enter image description here

and this is what I want

and this is what I want

My code:

import arcpy

lyrName = r"C:\Users\Moshe\Documents\ArcGIS\Default.gdb\D1"
Layer = "Layer"
RefName = "RefName"
startNumber = 1
listValue = []

with arcpy.da.SearchCursor(lyrName, Layer) as cursor:
    for row in cursor:
        value = row[0]
    list = list(dict.fromkeys(listValue))

Layer2 = "Layer"
RefName2 = "RefName"
with arcpy.da.UpdateCursor(lyrName, [RefName2, Layer2]) as cursor2:
    for i in list:
        print (i)
        for row2 in cursor2:
                if row2[1] in str(i):
                    row2[0] = startNumber
                    startNumber = startNumber + 1
                    print "updated row {}".format(row2[0])
        startNumber = 1
  • 1
    Your task is fraught with potential failures. There is no mandate that an UpdateCursor return records in a particular order if an ORDER BY is not specified. I suggest you change this multiphase update into a series of SearchCursor calls (with ORDER BY) to compile a dictionary of intended results, then use one UpdateCursor to modify values by rowid lookup.
    – Vince
    Jun 18, 2021 at 13:50
  • the order in my next stage. it will be determinate by the xy location. but for now. how can make this lookup?
    – moshe
    Jun 18, 2021 at 14:04
  • 1
    Use a dictionary
    – Vince
    Jun 18, 2021 at 14:10
  • Have a look at this q&a.
    – Hornbydd
    Jun 19, 2021 at 7:49
  • Or this gis.stackexchange.com/questions/200150/…
    – FelixIP
    Jun 22, 2021 at 2:42

1 Answer 1


This should do what you are wanting to do...

import arcpy

lyrName = r"C:\Users\Moshe\Documents\ArcGIS\Default.gdb\D1"    
fields = ["Layer", "RefName"]    
counter = 1
prevFieldValue = ""

with arcpy.da.UpdateCursor(lyrName, fields, sql_clause=(None, "ORDER BY Layer, RefName")) as cursor:
    for row in cursor:
        if row[0] == prevFieldValue:
            counter += 1
            counter = 1
        row[1] = str(counter)
        prevFieldValue = row[0]

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.