Select to view content in your preferred language

Adding two attribute fields together in an empty third field.

937
2
10-30-2013 07:23 AM
BrendanWhite
New Contributor
import arcpy, fileinput, os, string
from arcpy import env
env.overwriteOutput = True
env.workspace = "K:/Projects/Project Number/Points.shp"
fc = "shapefile.shp"
verification = arcpy.Exists (fc)
print verification
del verification

arcpy.Addfield_management (fc, "Field3", "DOUBLE", "", "", "", "", "", "", "")
fields = ("Field1", "Field2", "Field3")
with arcpy.da.UpdateCursor (fc, fields) as cursor:
    for row in cursor:
    row[0] = row[2+1]    
    cursor.updateRow(row)
del row
del cursor


Hello all.  I am attempting to use python to add a new attribute table column to the existing attribute table columns of a shapefile.  I have gotten this bit of code to work, as seen above and entitled "Field3."  I want to populate values in this new field by adding the values of two other fields, "Field1", and "Field2".  In other words, Field1+Field2=Field3.  I think I am almost there, but I suspect that my "row[2] = row[0+1]" is incorrect.  Any help would be extremely appreciated!
Tags (2)
0 Kudos
2 Replies
JakeSkinner
Esri Esteemed Contributor
You will just need to make a couple line changes:

with arcpy.da.UpdateCursor (fc, fields) as cursor:
    for row in cursor:
        row[2] = row[0] + row[1]
        cursor.updateRow(row)
del row
del cursor


Since 'Field3' is specified 3rd in your 'fields' variable, this should be referenced by 'row[2]'.  Also, be sure to indent the lines after 'for row in cursor'.
0 Kudos
XanderBakker
Esri Esteemed Contributor
In addition the points pointed out correctly by Jake, there are a few other things:

1) The "env.workspace" is pointing to a featureclass (shapefile) instead of a workspace. Better change this to
env.workspace = "K:/Projects/Project Number"

2) it is OK to check for the existence of the featureclass "shapefile.shp", but it won't work when the workspace is not correctly set

change:

verification = arcpy.Exists(fc)
print verification
del verification


to:

if arcpy.Exists(fc):
    # continue here with indented code



3) You import "fileinput, os, string", but since you don't use them, it may be better not to import those.

4) It is not necessary to delete the cursor since you are using a "with" statement.

5) it may be wise to check if the column exists before adding the field to avoid errors

outFld = "Field3"
if len(arcpy.ListFields(fc, outFld)) == 0:
    arcpy.Addfield_management (fc, outFld, "DOUBLE")



Kind regards,

Xander
0 Kudos