More

Using nested if statements in Python Parser of ArcGIS Field Calculator?

Using nested if statements in Python Parser of ArcGIS Field Calculator?


The solution in VB for the base process is at If/then VBScript/Python code equivalent to SQL IN ('x','y',z') expression in ArcGIS Field Calculator? works great but I was trying to nest 'if' statements and can't.

So pre-logic code of

if [grid_code] = 1 then f2= 2 end if if [grid_code] = 2 then f2=3.5 end if

… etc. but this doesn't work.

What am I doing wrong?

I tried the second 'if' before the 'end if' and also tried 'elif' but these give script errors.

Also I am seeing a warning message about "The calculated value is invalid for the row with objectID=1" and when you click click 'yes' to continue it works fine.


For VB, something like this should work, I think:

Pre-logic script code:

Dim f2 As Double If [grid_code] = 1 Then f2 = 2 ElseIf [grid_code] = 2 Then f2 = 3.5 End If

asp_code =

f2

In Python, I think it would be something like this (though I don't have ArcGIS 10 so I can't check):

Pre-logic script code:

def my_func(my_field): if my_field == 1: f2 = 2 elif my_field == 2: f2 = 3.5 return f2

asp_code =

my_func(!grid_code!)

The error message saying that the "calculated value is invalid" is a bit strange. Perhaps double-check that yourasp_codefield is offloatordoubledata type (notinteger), and that you have all of the options in the grid_code field covered by your if statements? Sorry if that's too obvious, but it's all I can think of at the moment. Good luck!


For Python syntax, I would suggest that you would want something like this with nested if… elif statements. As for the [grid_code] does it need to be enclosed in brackets? or is it a field? if it is a field, then I suspect that replacing [] with double quotes would do the trick

… you need a def (aka function call name passing a field name to the following if [grid_code] == 1: f2= 2 elif [grid_code] == 2: f2=3.5 return f2

Update… Of course boolean slicing is far easier in the field calculator, a demo, just insert ! marks around the field names (Gridcode, in this example, so it would be !Gridcode! in the field calculator)

>>> Gridcode = 1 >>> [3.5, 2.0][Gridcode == 1] 2.0

Watch the video: How to use field calculator in ArcMap with Python expression? Lecture