Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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.....
share|improve this answer

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", "")
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.