1
import arcpy, sys, itertools

arcpy.env.workspace = r'path to geodatabase'

fields1 = ['gearqty', 'cnemarea', 'fzone', 'qdsq', 'tensmsq', 'crew', 'nanglers', 'port', 'totalquant', 'trip_days', 'day_fracti', 'gear_days', 'qtykept', 'qtydisc', 'mean_hp', 'sd_hp', 'mean_len', 'sd_len', 'mean_gtons', 'sd_gtons', 'size_fleet', 'anon_id', 'fdays']
fields2 = ['gearqty1', 'cnemare1', 'fzone1', 'qdsq1', 'tensmsq1', 'crew1', 'nangler1', 'port1', 'tquant1', 'tripdays1', 'dayfract1', 'geardays1', 'qtykept1', 'qtydisc1', 'mean_hp1', 'sd_hp1', 'mean_len1', 'sd_len1', 'mean_gton1', 'sd_gtons1', 'sizefleet1', 'anonid1', 'fdays1']

# add new fields of type LONG
for fc in arcpy.ListFeatureClasses():
    for b in fields2:
        arcpy.AddField_management(fc, b, "LONG")

# calculate LONG fields from STR fields
for fc in arcpy.ListFeatureClasses(): 
    for a, b in itertools.izip(fields1, fields2):
        arcpy.CalculateField_management(fc, b, !a!) 

# delete all unnecessary string attributes
for fc in arcpy.ListFeatureClasses():
    for a in fields1:
        arcpy.DeleteField_management(fc, a)

The list of fields, fields1, is all string data, but it should be numeric. The first code block successfully created new LONG attributes using the names provided by fields2.

The second part is where I'm having trouble. I just need the new fields2 attributes to be calculated from the old fields1 attributes.

The third section should delete all of the attributes from fields1, as they are useless to me as strings. I haven't been able to test that part yet.

I've been testing this on one shapefile, but there will be 20+ shapefiles in the geodatabase.

  • what was the error you got when testing the second part? – Midavalo Jan 29 '16 at 20:41
3

!a! is not valid Python. Is this a typo?

Calculate Field defaults to the VB parser, so you'll want to change that to Python.

Something like the following should work: str.format() for reference.

arcpy.CalculateField_management(fc, b, "!{}!".format(a), "PYTHON_9.3")

To simplify things, you can combine all your for loops into one:

for fc in arcpy.ListFeatureClasses():
    for a, b in itertools.izip(fields1, fields2):
        # add new fields of type LONG
        # calculate LONG fields from STR fields
        # delete all unnecessary string attributes
        arcpy.AddField_management(fc, b, "LONG")
        arcpy.CalculateField_management(fc, b, "!{}!".format(a), "PYTHON_9.3")
        arcpy.DeleteField_management(fc, a)

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.