2

I have a table in a file geodatabase that has "FieldA" and "FieldB".

I want to update FieldB with one of two values, depending on if there are one or more records with the same value of FieldA.

Example:

FieldA   FieldB

   1        0

   2        1

   2        1

   3        0

I've tried this way

with arcpy.da.UpdateCursor(featureClass, ("FieldA", "FieldB")) as cursor:

for rupd in cursor:

    rows = [row for row in arcpy.SearchCursor(featureClass, 'FieldA=' + str(rupd[0]) )]

    if len(rows)>1:
        rupd[1]=0
    else:
        rupd[1]=1

    cursor.updateRow(rupd)

The table has around 100k records. It takes around 1 second each record.

Can this performance be improved?

1

Your code is slow because you have nested cursors so for each row in the updatecursor you are creating a searchcursor and reading rows. You are also using the old searchcursor (not da.) which is slow.

Instead first count all occurences once using collections.Counter. The result is is a dictionary with FieldA value as key and count as value, for example: {1:1, 2:2, 3:1}.

...an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

import arcpy
from collections import Counter

fc = r'C:\data.gdb\featureclass'
field1 = 'FieldA'
field2 = 'FieldB'

#Store count for each FieldA value in a dictionary
cnt = Counter()
with arcpy.da.SearchCursor(fc, field1) as cursor:
    for row in cursor:
        cnt[row[0]]+=1

#For every row check count in dictionary and update FieldB
with arcpy.da.UpdateCursor(fc,[field1, field2]) as cursor:
    for row in cursor:
        if cnt[row[0]]>1:
            row[1]=1
        else:
            row[1]=0
        cursor.updateRow(row)
  • 1
    Never used the counter. Great tip. Thank you so much. – Rui Neves May 29 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.