Thursday 24 January 2019

python - Using ListFields and CalculateField to find max value in variable number of fields to populate another field?


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.



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", "")

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...