arcpy.CalculateField_management - compare: how to return fieldvalues

671
6
Jump to solution
12-04-2018 03:36 AM
SilvanStöckli
New Contributor III

Hello


I use a python script to compare the value of a field like follows:

def compare(class1):

   if class1 in (612, 611):
       return "Text1"
   elif class1 == 617:
       return "Text2"
   else:
       return !Field!

(followed by arcpy.CalculateField_management....)

this works perfectly to return a standardized text like "Text 1" or "Text 2".

But what I really want to do is I want to return a field-value instead of a text.

If (612, 611) return Field1-value;

if (617) return Field2-value.

I tried it with !Field! instead of "Text 1" but it didn't work.

What's the code to return a fieldvalue instead of text?

Thanks for your help!

0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Esteemed Contributor
def compare(class1, another_value):

   if class1 in (612, 611):
       return "Text1"
   elif class1 == 617:
       return "Text2"
   else:
       return another_value

# Expression below

compare(!some_field!, !another_field!)

View solution in original post

6 Replies
DanPatterson_Retired
MVP Esteemed Contributor

You would have to change !Field1! to class1 since class1 is representing what you find in Field1 and your script as it stands, has no idea what Field1 is.  

0 Kudos
SilvanStöckli
New Contributor III

thanks for your help

the problem ist that I don't want to return the value from the field I'm comparing with but the value from an other field in the same table.

That's why I tried to use !"AnotherFieldName"! with those "!!"

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor
def compare(class1, another_value):

   if class1 in (612, 611):
       return "Text1"
   elif class1 == 617:
       return "Text2"
   else:
       return another_value

# Expression below

compare(!some_field!, !another_field!)
SilvanStöckli
New Contributor III

I thought I found the solution:

return arcpy.CalculateField_management(fc, field, "!AnotherFieldName!", "PYTHON_9.3", "")

But this calculates new values for the whole table instead of only for the ones with value 612 in "field"

Any idea?

Thanks for your help!

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Calculate Field is a set-based tool.  If you want to update only a subset of records, you need to either create a feature layer and apply a selection set or embed some logic into the code block.

0 Kudos
LukeWebb
Occasional Contributor III

Dan posted the solution, ill rewrite it more explicitly for your question.  You can pass as many values/fields to a function as you like so that you can then return their values.

def compare(class1, class2, class3):

   if class1 in (612, 611):
       return class2
   elif class1 == 617:
       return class3
   else:
       return class1

# Expression below

compare(!some_field!, !another_field!, !another_field2!)