2

I'm trying to work on my first arcpy script and am running into some troubles. The objective is to create a new field, check several existing fields (Cnt1,2,3 and Pop1,2,3) for missing data (-99 value) and if find missing data populate new field with a 0, if not then populate the field with the result from a simple calculation. From a separate related post I got some feedback that the problem was that I am concatenating the values, not adding them and this if-elif statement might need to be within a function and then called. Any advice greatly appreciated!

enter image description here

3
  • Are Cnt1, Cnt2, Cnt3, Pop1, Pop2, and Pop3 all fields in USCancer2000.shp? If so, then they are not referencing those fields right now. They are just strings referencing nothing. Commented Apr 5, 2013 at 16:05
  • yes blord, they are all fields, I was under the impression that "..." represented a field, is this not correct?
    – David Meek
    Commented Apr 5, 2013 at 16:33
  • Not in a script, no. See the script below to see how I use the field name with a cursor to access values using getValue and set values using setValue, all against a row object Commented Apr 5, 2013 at 16:43

2 Answers 2

6

This was a fun python problem to illustrate the workflow on.

I might update this later to cleanup the exception handling when you calculate the field. The comments show what I am doing at each step of the script.

import arcpy, sys

#Let's start with using a workspace. This will make later work easier
arcpy.env.workspace = "C:\\gislab2\\Python\\take_home\\"
shapefile = "USCancer2000.shp"
field_name = "Henry1"
#Validate field name
field_name = arcpy.ValidateFieldName(field_name)
#Make sure our shapefile exists
if not arcpy.Exists(shapefile):
    sys.exit("Input shapefile " + shapefile + " does not exist in workspace " + arcpy.env.workspace + ". Cannot continue.")
#Check if field exists already, and delete it if it does
if (len(arcpy.ListFields(shapefile, field_name)) == 1):
    arcpy.DeleteField_Management(shapefile,field_name)
#Add the field
arpcy.AddField_management(shapefile,field_name,"LONG", "","","","","NULLABLE","NON_REQUIRED","")
#Rather than use CalculateField, the logic involved makes this better suited for a cursor
cursor = arcpy.UpdateCursor(shapefile)

for row in cursor:
    #Get the value of each of our fields, and put them into variables
    c1 = row.getValue("Cnt1")
    c2 = row.getValue("Cnt2")
    c3 = row.getValue("Cnt3")
    p1 = row.getValue("Pop1")
    p2 = row.getValue("Pop2")
    p3 = row.getValue("Pop3")
    #check for missing values, assuming that non-missing values are all greater than or equal to zero
    #also make sure we are not going to divide by zero
    try: #The try allows us to catch errors so we can bail out and still set the field to zero
        if((min(c1,c2,c3,p1,p2,p3) < 0) or ((p1+p2+p3) == 0) ):
            field_value = 0
        else:
            print "Calculating (" + "+".join([str(c1),str(c2),str(c3)]) + ")/(" + "+".join([str(p1),str(p2),str(p3)]) + ")"  #This is a debugging line, can remove once works properly.
            field_value = 1.0 * (c1+c2+c3)/(p1+p2+p3)
    except:
        #If something goes wrong, set the value to 0 still
        field_value = 0
    #Set the value of Henry1 for just this row
    print "Setting '" + field_name + "' to " + str(field_value) #This is a debugging line, can remove once works properly.
    row.setValue(field_name,field_value)
    cursor.updateRow(row)
    #At this point, we look back to the type of the for-in statement and do the next row in the shapefil

#Do cleanup at the end
del row
del cursor
10
  • wow blord, i can't thank you enough, i think I'll need to reflect on this a bit to make sure I understand, but doing so will surely be a good learning experience!
    – David Meek
    Commented Apr 5, 2013 at 17:11
  • blord, I am running into an instant error due to the exit clause, because the system is saying that the file doesn't exist. I've copy/pasted the path, confirmed the spelling of the file is exactly the same as in the code, tried deleting the .shp, but it still is exiting with this error. Any suggestions?
    – David Meek
    Commented Apr 5, 2013 at 17:29
  • Whoops, shapefile should not be in quotes. Not sure how I did that. Changed. Commented Apr 5, 2013 at 18:20
  • oddly, to me, the script runs when imported into arcgis, but not in python IDLE. However, it doesn't seem to run correctly there either as it populates the field with 6 across all rows. any idea why?
    – David Meek
    Commented Apr 5, 2013 at 18:22
  • What is the error in IDLE? What are the values for c1,c2,c3,p1,p2,p3 for a sample row? Commented Apr 5, 2013 at 20:04
1

It looks like your script is attempting to rename the column name rather than the field value. Given that the column is named "Henry1" and your Cnt or Pop values are -99, then your Henry1 would change to 0, else the name would be converted to another numeric value.. or if there are strings in the Cnt or Pop values Python would be expected to add and divide them. You need to define a variable other than "Field_name" for your field values, and then focus on a function to calculate those field values.

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.