TransWikia.com

UpdateCursor with multiple loops in ArcPy

Geographic Information Systems Asked by moshe on July 10, 2021

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:UsersMosheDocumentsArcGISDefault.gdbD1"
Layer = "Layer"
RefName = "RefName"
startNumber = 1
listValue = []


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

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
                    cursor2.updateRow(row2)
                    print "updated row {}".format(row2[0])
        startNumber = 1

One Answer

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

import arcpy

lyrName = r"C:UsersMosheDocumentsArcGISDefault.gdbD1"    
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
        else:
            counter = 1
        row[1] = str(counter)
        cursor.updateRow(row)
        prevFieldValue = row[0]

Answered by Jason Miller on July 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP