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.
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
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
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!)
Les membres connectés peuvent publier, suivre les mises à jour, et plus encore. Nouveau ici ? Inscrivez-vous gratuitement.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.