Python if then codeblock in field calculator

4672
5
Jump to solution
09-14-2015 07:45 AM
KeithAddison1
Occasional Contributor III

I need to write an if then code block for field calculator to see if the value in field A equals 0, and if it is to make the value in field B equal -1.  Else do nothing.  How can I do this?  FIeld A is type float & field B is type interger.

0 Kudos
1 Solution

Accepted Solutions
RyanClose
New Contributor III

Assuming you are using ArcMap since you mentioned field calculator:
Right click the field you wish to change to -1 and calculate that field.

Switch the radio button to Python

In the code block enter:

def changefield(whatif,okthen):

  if (whatif == 0):

    okthen = -1

  return okthen

Then in the text box below FIELDB  =

Enter: changefield(!FIELDA!, !FIELDB!)

View solution in original post

0 Kudos
5 Replies
DanPatterson_Retired
MVP Emeritus

They can be emulated using this syntax

simple comparison and reclass

  " True condition " if !some_field! == "some_value" else " False condition "

ie .  "Agricultural 10 Acres" if !Zone! == "A-10" else "False"

1  if !A! == 0 else -999

assuming you are calculating in the B field, using python and you can't do nothing...so I put in -999 and you can replace it with integer nothingness

RyanClose
New Contributor III

Assuming you are using ArcMap since you mentioned field calculator:
Right click the field you wish to change to -1 and calculate that field.

Switch the radio button to Python

In the code block enter:

def changefield(whatif,okthen):

  if (whatif == 0):

    okthen = -1

  return okthen

Then in the text box below FIELDB  =

Enter: changefield(!FIELDA!, !FIELDB!)

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Python has conditional expressions, a.k.a., ternary operators, that can be used in situations like this one.  Using a ternary operator eliminates the need for using a code block and defining a function.

-1 if !FieldA! == 0 else !FieldB!

DanPatterson_Retired
MVP Emeritus

hmmm my previous thoughts exactly 

0 Kudos
RyanClose
New Contributor III

Excellent. Nice to know!

0 Kudos