2

In a counties shapefile, I have two fields named population2001 and population2010. I would like to create a third field with the difference between 2001 and 2010 using arcpy and the update cursor to better learn how to use cursors. My code:

 import arcpy
 arcpy.env.workspace = 
 r"C:\Users\Documents\geodatabase.gdb"
 ndCounties = r"C:\Users\Documents\geodatabase.gdb\Counties"
 #add the new field
 arcpy.AddField_management(ndCounties, "difference", "LONG", field_length = 10)
 fields = ['POP2001', 'POP2010', 'difference']
 with arcpy.da.UpdateCursor(ndCounties, fields) as cursor:
 for row in cursor:
 if row[0] == 'POP2001':
 row[1] = 1
 row[2] = 2
 elif row[0] == 'POP2010':
 row[1] = 2
 row[2] = 3
 row[3] = row[1] - row[2]
 cursor.updateRow(row)

When I run this code, I get this error:

TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'

I'm not exactly sure if this is the right way of doing this field subtraction.

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Oct 3, 2016 at 19:48
1
  • 1
    As a side note, the field_length parameter for AddField_management is only applicable on fields of type text or blob. Commented Oct 3, 2016 at 20:01

1 Answer 1

4

In your cursor the row followed by the number references each field:

  • row[0] references POP2001 field
  • row[1] references POP2010 field
  • row[2] references difference field

You do not have a fourth field to reference with row[3].

What you want to do is subtract row[0] from row[1] to get the difference to put into row[2].

for row in cursor:
 row[2] = abs(row[1] - row[0])
 cursor.updateRow(row)

The abs() gives an absolute value. If you want to see where population has gone down (a negative difference) remove the abs():

row[2] = row[1] - row[0]
answered Oct 3, 2016 at 19:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.