0

Why does the field populate with the same number, but prints correclty?

import arcpy
import rivers
arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"C:\Data"

import math
def sinuosity(shape):
    channel = shape.length
    deltaX = shape.firstPoint.X -shape.lastPoint.X
    deltaY = shape.firstPoint.Y -shape.lastPoint.Y
    valley = math.sqrt(pow(deltaX, 2) + pow(deltaY, 2))
    return channel/valley

fc = "streams.shp"
new_field = "Sindex"
with arcpy.da.SearchCursor(fc, ["OID@", "SHAPE@"]) as cursor:
        for row in cursor:
            oid = row[0]
            shape =row[1]
            si = rivers.sinuosity(shape)
            print (f"Stream ID {oid} has an sinuosity index of {si:.3f}")

arcpy.AddField_management (fc, new_field, "DOUBLE" )
arcpy.CalculateField_management(fc,new_field, si)
5
  • 1
    Welcome to gis.stackexchange.com. I recommend you to explain your issue in more detail.
    – BBG_GIS
    Commented Dec 9, 2019 at 17:44
  • 1
    When you say it populates with the same number are you referring to the table you are already looking at in ArcMap? You may need to close the table and re-open it to see it update; perhaps even save your edits first then re-open.
    – John
    Commented Dec 9, 2019 at 17:47
  • Welcome to GIS SE! As a new user please take the tour.
    – Midavalo
    Commented Dec 9, 2019 at 18:16
  • I'll add more detail. The field in the attribute table had the same value for every record.
    – Jessica
    Commented Dec 9, 2019 at 20:24
  • Add this extra information to you original question post (use the 'Edit' butotn at the bottom of the question). Not just in comments which people may not read. Commented Dec 9, 2019 at 21:10

1 Answer 1

4

Your print() is inside a SearchCursor. In your SearchCursor you also define the variable si for your CalculateField. So you write in CalculateField_management for all features the last si from the SearchCursor.

SearchCursor can not modify rows. Try it with an arcpy.da.UpdateCursor():

# not tested
fc = "streams.shp"
new_field = "Sindex"
arcpy.AddField_management(fc, new_field, "DOUBLE" )
with arcpy.da.UpdateCursor(fc, ["OID@", "SHAPE@", new_field]) as cursor:
        for row in cursor:
            oid = row[0]
            shape =row[1]
            si = rivers.sinuosity(shape)
            # set si for new_field
            row[2]=si
            print (f"Stream ID {oid} has an sinuosity index of {si:.3f}")
            # save / update the actual row
            cursor.updateRow(row) 
2
  • Thank you! This helped lot.
    – Jessica
    Commented Dec 9, 2019 at 20:23
  • If this has resolved the question, then mark this answer as correct by clicking on the tick/check mark next to the answer. Commented Dec 9, 2019 at 21:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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