I am having some trouble getting a search cursor to return a value for each record. The purpose of my code is to scan through a list of records in a field (FieldA) and based on those values populate a second field (FieldB) with a random number between 1 and the value in FieldA. FieldA contains numeric values which vary depending on their association. My code is as follows:

CursorA = arcpy.SearchCursor(FC)
for row in cursorA:
    rowcount =(row.getValue("FieldA"))
    row = cursorA.next()
    cursorB = arcpy.UpdateCursor(FC, "FieldB") 
    for rowB in cursorB:
        rowB[0] = randint(1, rowcount)

When I run the code it appears as though the searchcursor locates the value of the last record in FieldA and uses that value as the highest value in the random sequence. I could be wrong on this however, and it could be related to improper coding on my part.


This attached script shows the approach I would take. The main operator here is the UpdateCursor itself. You can see that I included both fields within one UpdateCursor. In the UpdateCursor, this translates to:

row[0] = 'FieldA'
row[1] = 'FieldB'

Then simply use these rows to do the heavy lifting for you:

rnumber = randint(1, row[0])

import arcpy, random
from random import *

fc = r'C:\path\to\fc'

with arcpy.da.UpdateCursor(fc, ['FieldA','FieldB']) as cursor:
    for row in cursor:
        rnumber = randint(1, row[0])
        print rnumber
        row[1] = rnumber

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.