4

I need some assistance with the syntax for a CalculateField_management calculation as I have still yet to master all the python syntax rules.

What I am trying to do is find the max value in a variable number of fields in order to populate another field. I am using the ListFields function to discover the desired fields to choose from, but getting that list into the formula is giving me some difficulty.

import arcpy, os, string
LAYERS = arcpy.GetParameterAsText(0)
SLOSHFILEDS = [f.name for f in arcpy.ListFields(LAYERS,"","DOUBLE")
arcpy.CalculateField_management (LAYERS, "MAXSURGE", max(SLOSHFILEDS))

I have tried any number of different string combinations for the max() calc to no avail (not that this particular variation shows that).

Adding/Changing the following to the script doesn't give me the syntax error that I would recieve with the above, but it does give me a "The calculate value is invalid for the row with ObjectID = 0..." x 18,526 (or however many rows are in my table) and then does nothing to the table except populate my MAXSURGE field with 0's.

SLOSHFILEDS = arcpy.ListFields(LAYERS,"","DOUBLE")
fieldNameList = []
for field in SLOSHFILEDS:
        if not field.required:
            fieldNameList.append(field.name)
arcpy.CalculateField_management (LAYERS, "MAXSURGE", max(fieldNameList))

Hard coding the field names into the formula works great, but of course, I will not always have the same number of fields or same field names to work with.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
NCFMP
  • 103
  • 9

2 Answers2

3

I figured out the problem (with help, of course). I needed to convert the list object to a string using the .join function.

import arcpy, os, string
LAYERS = arcpy.GetParameterAsText(0)
SLOSHFILEDS = arcpy.ListFields(LAYERS,"","DOUBLE")
fieldNameList = []
for field in SLOSHFILEDS:
        if not field.required:
            fieldNameList.append(field.name)
SLOSHSTRING = "!" + "!, !".join(fieldNameList) + "!"
calculation = "max(" + SLOSHSTRING + ")"
arcpy.CalculateField_management (LAYERS, "MAXSURGE", calculation, "PYTHON", "")
NCFMP
  • 103
  • 9
1

The first step is to incorporate conditional logic (e.g. if statement) within your loop to look for the field name that you want to run your calculation on.

e.g.

fieldName = arcpy.GetParameterAsText(0)

for field in SLOSHFILEDS:
    if field.name == fieldName: 
        arcpy.CalculateField_management.....
artwork21
  • 35,114
  • 8
  • 66
  • 134