1

Im not sure how to pass through a list of fields within the calculate field tool.I have a list of fields and each of them need to be divided by 1000. My code is as follows:

import arcpy
shp = r"m\team.shp"
fields = arcpy.ListFields(shp, "*qty")
for f in fields:
    print f.name
    arcpy.CalculateField_management(shp, f, "f/1000", "PYTHON")
  • 3
    You do not say how many fields you have but I suspect that if it is more than a few then using arcpy.da.UpdateCursor() to do them all in one pass will be the way to go. – PolyGeo Apr 19 '16 at 10:33
  • How do I use the updatecursor.da to achieve the same objective? Is this a far quicker way of updating rows? – MacroZED Apr 19 '16 at 10:55
  • Check out the samples in the help at desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-data-access/… I suspect that the more fields you have the better it will be to use arcpy.da.UpdateCursor(). For one, or maybe a few fields I suspect CalculateField may be quicker but I have not performance timed it. – PolyGeo Apr 19 '16 at 11:14
4

You want to pass your field name f.name as the name of the field, and then add that to your expression as well. In the field calculator you need to surround your field name with exclamation marks e.g. !myfield!

I think something like this should work:

import arcpy
shp = r"m\team.shp"
fields = arcpy.ListFields(shp, "*qty")
for f in fields:
    print f.name
    arcpy.CalculateField_management(shp, f.name, "!{}!/1000".format(f.name), "PYTHON_9.3")

NOTE: Be aware that you are overwriting your existing field value with the new value, not calculating into a new field.

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.