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.
-
1As a side note, the field_length parameter for AddField_management is only applicable on fields of type text or blob.Brian– Brian2016年10月03日 20:01:54 +00:00Commented Oct 3, 2016 at 20:01
1 Answer 1
In your cursor the row followed by the number references each field:
row[0]
referencesPOP2001
fieldrow[1]
referencesPOP2010
fieldrow[2]
referencesdifference
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]