8

I need to add values to an existing field in the attribute table. The values are to be determined by values in another field in the same attribute table. I am unable to define the values in another field in the script. Can anyone help me with it?

7

I've not used Arc 10.1 cursors, but it's apparently even easier there.

In 10.0, there are a few ways to go about it, but here's a basic, beginner's approach:

# Create a cursor on a feature class
cur = arcpy.UpdateCursor(myFeatureClass)

# Loop through the rows in the attribute table
for row in cur:
    # The variable sqMiles will get the value from the column
    # named 'Area_Miles'
    sqMiles = row.getValue('Area_Miles')
    # Calculate how many acres
    acres = (sqMiles * 640)
    # Assign the acres to a column named 'Area_Acres'
    row.setValue('Area_Acres', acres)
    # Apply the change
    cur.updateRow(row)

    # The loop will then move on to the next row/feature

A simpler, condensed version:

cur = arcpy.UpdateCursor(myFeatureClass)

for row in cur:
    row.setValue('Area_Acres', row.getValue('Area_Miles') * 640)
    cur.updateRow(row)

See: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//000v0000003m000000

  • 4
    Tom, please re-write ALL of ESRI's "Help Files" using the method you used in this answer. Then more people will understand, and the world will be a happier place. – Jason Miller Jun 27 '13 at 14:58
  • 1
    Tom, please follow @JasonMiller 's advice. And thank you VERY much for cracking this down for us. I considered myself illiterate, but now no more. – FaCoffee Jan 20 '17 at 12:35
2

Well, there are a few ways you can do this.

  1. If the calculation is fairly simple, I would use the Calculate Field tool. If you need to use the code_block parameter, I'd go with option #2 as it's not always easy getting the syntax correct in a script (or in the tool itself for that matter).

  2. If you are interested in scripting more in the future, I'd strongly recommend using cursors. You can write the values from one field into a Python list and perform your calculations on each item in the list with a for loop and then write the list back to your new field.

I rarely use Calculate Field anymore as it's easier to script cursors for all but the simplest formulas.

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.