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.

  • 1
    As a side note, the field_length parameter for AddField_management is only applicable on fields of type text or blob. – Brian Oct 3 '16 at 20:01
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]

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.