0

I have a polyline feature class with this attribute table:

enter image description here

I need to get values without decimal numbers.

I created a new field called "newLength" and tried to insert the new values (whole numbers only) with this code:

import arcpy

# add new field
arcpy.env.workspace = "G:\desktop\Project\lyr\New File Geodatabase.gdb"
arcpy.AddField_management("dis", "newLength", "LONG")

fc = r"G:\desktop\Project\lyr\New File Geodatabase.gdb\dis"
with arcpy.da.UpdateCursor(fc, "Shape_Length") as cursor: # second argument = field name
    for row in cursor:
       newValue = '%.0f' % float(str(row).strip('[]')) # convert list to string

# add the new numbers to the new field
with arcpy.da.UpdateCursor(fc, "newLength") as cursor: # second argument = field name 
   for row in cursor:
      cursor.updateRow([newValue])

but the error is a new field with the same values in all rows:

enter image description here

whereas the second row is true and the first row is an error

2 Answers 2

4

You are only filling in the last value of "newValue" in all the rows. Try to modify it this way;

import arcpy

# add new field
arcpy.env.workspace = "G:\desktop\Project\lyr\New File Geodatabase.gdb"
arcpy.AddField_management("dis", "newLength", "LONG")

fc = r"G:\desktop\Project\lyr\New File Geodatabase.gdb\dis"


# add the new numbers to the new field
with arcpy.da.UpdateCursor(fc, ["Shape_Length", "newLength"]) as cursor: # second argument = field name 
   for row in cursor:
      newValue = '%.0f' % float(str(row[0]).strip('[]')) # convert list to string
      row[1] = newValue
      cursor.updateRow(row)

2

Your approach is overkill and the looping flawed. Add the new field as you have done and then simply run the calculate field tool and set the expression to be:

round(!Shape_Length!,0)

This will truncate the value, no need for any code. If you need to run this logic as a python script then simply right click on the tool result in the results panel and copy snippet, you'll have the code pre-formatted and ready to run.

1
  • where i add this line in the code please?
    – newGIS
    Commented Oct 17, 2023 at 10:47

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.