I need to subtract a value from a field and return that value to the new field, but if the value is below 0 simply return 0. I know I can do this with calculate field but I am unsure of how to write this in Python.
Example:
3200-1200=2000
800-1200=0
1211-1200=11
80-1200=0
Thanks for any help.
Solved! Go to Solution.
As a one-line function:
def sub_to_zero(a, b): return a - b if a > b else 0
can use the max() function.
Takes the max value. Since 0 is larger than any negative number, will return 0
R_
As a one-line function:
def sub_to_zero(a, b): return a - b if a > b else 0
David just beat me to posting with a very concise option, but here's a multiline option which does the same thing (this part goes in the code block):
def fancy_subtract(subtract_from):
value = 1200 #define value here
if subtract_from < value:
return 0
else:
diff = subtract_from - value
return diff
In a field calculation, you can use this by calling the function on your field:
fancy_subtract(!field_name!)
There is probably a more elegant or 'pythonic' way to do this but this will do what you want I think:
def calc_sub(num1, num2):
out = num1-num2
if out < 0:
ret_val = 0
else:
ret_val = out
return ret_val
#test using the following:
x = 10
y = 8
print(calc_sub(x,y))#should return 2
print(calc_sub(y,x))#should return 0
can use the max() function.
Takes the max value. Since 0 is larger than any negative number, will return 0
R_