Thursday, 10 August 2017

arcgis 10.1 - Using search and update cursors for random number generation in ArcPy?


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)
cursorB.updateRow(rowB)


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.



Answer



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
cursor.updateRow(row)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...