1

I have a piece of code where the goal is to search through the field names within a feature, select any field based on a specific character (in this case "z") and then use that selected field within a Field Calculator Expression. My experience with python is limited, see the code below;

for var in List_Input:

filename = os.path.splitext(os.path.basename(str(var)))[0]
arcpy.Select_analysis(var, env+"\\"+filename, "")
var_sel = env+"\\"+filename
arcpy.AddField_management(var_sel,"VR_Rate","Double")
VRField = arcpy.ListFields(var_sel,)

VRField_Calc = ""
for field in VRField:
    if "z" in field.name:
        VRField_Calc = field.name
        arcpy.CalculateField_management(var_sel,"VR_Rate", [VRField_Calc+" + 2"])

The bottom half of the code is where the issues arise. How to pass the "VRField_Calc" (field name) into the Calculate Field Expression?

  • You need to tell it which field. "VR_Rate" should be the VRField_Calc variable. – Barbarossa Jul 16 '15 at 13:19
  • the function works as follows; CalculateField_management (in_table, field, expression, {expression_type}, {code_block}) within my equation var_sel = input table, "VR_Rate" = field. I just need to know how to pass the VRField_Calc (variable containing the found field) into the Expression. I am intentionally calculating the "VR_Rate" field. I wish for it to contain VRField_Calc +2 (in this example). – user52640 Jul 16 '15 at 13:25
  • Fantastic, thank you for you help. This works great! – user52640 Jul 16 '15 at 13:38
2

Try this:

arcpy.CalculateField_management(var_sel, "VR_Rate", '!' + VRField_Calc + '! + 2', "PYTHON_9.3")

To search for a specific field before calculating:

findField = 'some_field_name'

for field in VRField:
if field.name == findField:
    arcpy.CalculateField_management(var_sel, "VR_Rate", '!' + field.name + '! + 2', "PYTHON_9.3")
  • What about searching for a specific field name before calculating? – artwork21 Jul 16 '15 at 13:52
  • @artwork21 See edits. – Barbarossa Jul 16 '15 at 14:07

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.