Select to view content in your preferred language

Python code to subtract a value but don't go below 0

1431
4
Jump to solution
01-11-2024 12:02 PM
FlightDeck
Occasional Contributor

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. 

0 Kudos
2 Solutions

Accepted Solutions
DavidSolari
Frequent Contributor

As a one-line function:

def sub_to_zero(a, b): return a - b if a > b else 0

View solution in original post

RhettZufelt
MVP Notable Contributor

can use the max() function.

RhettZufelt_0-1705006943843.png

Takes the max value.  Since 0 is larger than any negative number, will return 0

R_

View solution in original post

4 Replies
DavidSolari
Frequent Contributor

As a one-line function:

def sub_to_zero(a, b): return a - b if a > b else 0
rwrenner_esri
Esri Alum

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!)

 

0 Kudos
clt_cabq
Frequent Contributor

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
0 Kudos
RhettZufelt
MVP Notable Contributor

can use the max() function.

RhettZufelt_0-1705006943843.png

Takes the max value.  Since 0 is larger than any negative number, will return 0

R_