Friday 15 January 2016

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.



Answer



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 your asp_code field is of float or double data type (not integer), 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!


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...