I am trying to populate a field [Hazard] based on the values in two other fields [Depth2D] and [Speed2D].
I have managed to write a code block in VB script that works but I really want to figure out how to write it in Python. I cannot seem to get it right.
Underneath is the current iteration of my attempt at python, from what I have seen I need to define the variables to use, but can't seem to define things right.
The VB Script code block is as follows -
Dim hazard
If [DEPTH2D]<0.1 Then
hazard = 1
elseif [DEPTH2D]>=0.1 AND [DEPTH2D]<0.2 AND [SPEED2D]<2 Then
hazard = 2
else
hazard = 3
end if
The Python code block I have tried is as follows
def ifBlock(depth2d,speed2d)
if: depth2d < 0.1
return 1
elif: depth2d >=0.1 AND depth2d <0.2 AND speed2d<2
return 2
else:
return 3
I then have
ifBlock([DEPTH2D],[SPEED2D])
in the formula box
The error I am getting in the results window is ERROR999999; Syntax Error
2 Answers 2
You could define a function with your logic, as in:
def hazLevel(speed, depth):
if depth < 0.1:
return 1
elif (depth < 0.2 and speed < 2):
return 2
else:
return 3
...and in your field calculator form, toward the bottom should be a single line to enter your 'call' the above function (which should be copied to the code logic box. The single line call in this case feeds in the 2 fields for depth and speed:
hazLevel(!Speed2D!, !Depth2D!)
For the Python parser, the '!' delimits the fields...don't forget those, and to tick the Python parser in the field calculator window, as well as maintain proper indentation as shown.
-
hi there, thanks heaps for the help, your suggestion works. I ran it as you have written it and then also by adjusting mine to fit the same format - putting the colons at the end of each if/elif/else line, putting the multi-condition elif in brackets, and changing the delimiters to '!'. So thank you very much for that.ALiOAWA– ALiOAWA2017年02月24日 04:22:12 +00:00Commented Feb 24, 2017 at 4:22
This logic is hard to program, this is why I am using these polygons, where Y is depth and Y is velocity.
Convert relevant fields data into points, accordingly and do a spatial join to above polygons to calculate hazard
-
Think you mean X is speed, not Y for both; +1 for the nice visual although the yellow stripe should be the same thickness as the blue.... Also, in the OP's logic the 'else if' line can leave out the >= 0.1 because the < 0.1 condition is already taken care of in the if clauseT. Wayne Whitley– T. Wayne Whitley2017年02月07日 03:05:26 +00:00Commented Feb 7, 2017 at 3:05
-
Yes of course, X is speed. In regards of actual polygons shape I simply took ones from actual project. Hazard definitions vary from client to client. This is to show concept and often shapes are way more complicatedFelixIP– FelixIP2017年02月07日 03:21:21 +00:00Commented Feb 7, 2017 at 3:21
Explore related questions
See similar questions with these tags.
elseif
is not valid in python. useelif
.