1

I'm pretty novice at Python and I'm trying to employ a search cursor to round a field in a table in ArcGIS.

cursor = arcpy.SearchCursor(table,'', '', 'Distance')

for row in cursor:
    round(cursor, 3)

I'm receiving a "TypeError: a float is required" message.

Does anyone have any suggestions?

2
  • 2
    Use the DataAccess form (`arcpy.da.SearchCursor) instead of the deprecated old-style SearchCursor for all new development. Even if your syntax was correct, it wouldn't do anything, since the rounded value isn't used. Did you intend to use an UpdateCursor, instead? FieldCalculator would probably be a better solution here.
    – Vince
    Jul 13, 2018 at 15:01
  • 2
    As @Vince mentioned, using the data access version of the cursors is better. if you just want to test what the results would be (without updating) you can modify your search cursor (e.g. searchRows = arcpy.da.SearchCursor(table, ["Distance"]), but would need to reference the actual field within the row in your loop, not the overall cursor (e.g. for row in searchRows: print(round(row[0], 3)). If you want to update these values in your table, use Field Calculator or update cursor.You're getting the TypeError because you're passing the cursor itself.
    – SMiller
    Jul 13, 2018 at 15:06

1 Answer 1

3

@smiller is correct: row in your code is essentially a tuple, which doesn't have a 'round' method. The following syntax should work. It uses an update cursor and assumes you want to replace the non-rounded values with rounded ones:

with arcpy.da.UpdateCursor(table, ["Distance"]) as cursor:
    for row in cursor:
        row[0] = round(float(row[0]), 3)  # Uses float() in case distance is a string            
        cursor.updateRow(row)

If you'd like to make a new attribute for the rounded result:

arcpy.AddField_management(table, "Rounded", 'DOUBLE')
with arcpy.da.UpdateCursor(table, ["Distance", "Rounded"]) as cursor:
    for row in cursor:
        row[1] = round(float(row[0]), 3)
        cursor.updateRow(row)
4
  • 1
    You could use row[0] = round(float(row[0]), 3) to ensure the operation will work. Also, it may be preferable to add a new field with the rounded values.
    – Aaron
    Jul 13, 2018 at 19:25
  • 1
    Good suggestion! I have integrated it into the answer.
    – Matt
    Jul 13, 2018 at 19:30
  • 1
    A minor detail, row of OP is an arcpy.row object whereas the row yielding from arcpy.da is a tuple.
    – fatih_dur
    Jul 13, 2018 at 23:48
  • @fatih_dur Thanks for the correction! Answer updated.
    – Matt
    Jul 14, 2018 at 0: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.