Select to view content in your preferred language

Update Cursor to Calculate Field

1140
3
12-07-2013 08:09 AM
KevinWilliams
New Contributor
I'm trying to use an update cursor to calculate a field. Basically, I'm trying to avoid division by 0 by looking in row[0] and see if it's 0. My code thus far is:

import arcpy
fc="C:/Temp/crimeGrid.shp"
fields="'MEAN_GRIDC', 'SUM_Join_C', 'crimeRate')
with arcpy.da.UpdateCursor(fc,fields) as cursor:
    for row in cursor:
        if (row[0] > 0):
            row[2] = row[1]/row[0]
        else:
            row[2] = 0
        cursor.updateRow(row)


Any ideas or help on what I'm missing? I presume that it's the calculation aspect of my code.
Tags (2)
0 Kudos
3 Replies
by Anonymous User
Not applicable
You need to pass the fields variable in as a python list type (using [ ] ).  See more about python types [url=http://docs.python.org/2/tutorial/datastructures.html]here[/url].

import arcpy
fc = "C:/Temp/crimeGrid.shp"
fields = ['MEAN_GRIDC', 'SUM_Join_C', 'crimeRate']
with arcpy.da.UpdateCursor(fc,fields) as cursor:
    for row in cursor:
        if row[0] > 0:
            row[2] = row[1]/row[0]
        else:
            row[2] = 0
        cursor.updateRow(row)


This should do the trick.
0 Kudos
KevinWilliams
New Contributor
I tried your suggestion, but still no luck. However, looking at the ArcGIS 10.1 resource documentation, it should be as shown. I can't help but think it has something to do with the division of the rows... row[2] = row[1]/row[0].
0 Kudos
KevinWilliams
New Contributor
Sorry for the ridiculous question. I continually thought it was in the division of rows, so I looked into my fields a little closer. Turns out, Row[0] and Row[1] were Double and Row[2] was Long. Fixed that aspect and the code works as is.
0 Kudos