I am trying to update one field with values as multiples of five till the maximum for the value in the gridcode. The field I am trying to populate is called Time_min. As I am very new to python, am not able to understand where the mistake is. The overwrite is on, so it should not have any problems accessing the file. Please let me know if there are better alternatives.

rows = arcpy.UpdateCursor("CalculateT")
i = 5.0
time_min = Raster("time_min")
m = time_min.maximum
for row in rows:
    while i <= m:
        if row.getValue("gridcode") <= i:
            row.setValue("Time_min", i)
            i = i + 5
del row
del rows

I have also thought of putting the algorithm as checking divisible by 4 or not; but I need to know if this is normal or an error in my part.

  • 2
    Where is the feature class or table that you are running this on stored? Are you aware of arcpy.da.UpdateCursor() which I suspect will run about 20 times as fast as arcpy.UpdateCursor()?
    – PolyGeo
    Apr 6 '20 at 23:18

This code can get you stuck in an infinite loop if your gridecode value is never <= i.

while i <= m:
    if row.getValue("gridcode") <= i:

You're also updating your rows repeatedly, checking each increment of 5. Use modulo operation (%) instead to find and subtract the remainder.

>>> 37 % 5
>>> 37 - 37 % 5
>>> 100 - 100 % 5

Use a data access update cursor as well to speed things up.

with arcpy.da.UpdateCursor ("CalculateT", ["gridcode", "Time_min"]) as curs:
    for code, tm in curs:
        tm = min ([code - code % 5, m - m % 5])
        row = (code, tm)
        curs.updateRow (row)
  • Also, he can move the i increment out of the if statement.
    – Mathwiz
    Apr 13 '20 at 17:45

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.