Select to view content in your preferred language

Script to turn errors into no data (Desktop 10.3)

3198
13
Jump to solution
01-15-2016 10:27 AM
SteveCline
Occasional Contributor

I am running a field calculation which is [field A]/[field B].  Some of the values in field B are zero.  Is there a script I could use to turn results in the calculation where the denominator is zero into -99 instead of creating an error message?

0 Kudos
13 Replies
DarrenWiens2
MVP Honored Contributor

Oh, that's probably a function of integer/integer=integer. If you change one to float it should return a float (float/integer=float and integer/float=float):

def my_function(numerator, denominator):      
  if denominator == 0:      
    return -99    
  else:    
    return float(numerator)/denominator  
SteveCline
Occasional Contributor

That did it.  Thanks for the help.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

For simple cases like this, a Python Conditional Expression can be used directly in the field expression box, removing the need for a code block:

-99 if !TOSCH04! == 0 else float(!CHSCH04!)/!TOSCH04!

SteveCline
Occasional Contributor

Thanks for the advice.  Here is an additional step:

I would like to code an additional field (CHPROPSC) with multiple missing values.  Essentially, if the value in PRCHSCH04 is -99 only then CHPROPSC = -98.  If the value in PRCHSCH13 is -99 only then CHPROPSC = -97.  If the value in both is -99 then CHPROPSC = -99.  Otherwise CHPROPSC = PRCHSCH13 - PRCHSCH04.

I tried this but there was a processing failure:

-97 if !PRCHSCH13! == -99 & !PRCHSCH04! <> -99

-98 elif !PRCHSCH13! <> -99 & !PRCHSCH04! == -99

-99 elif !PRCHSCH13! == -99 & !PRCHSCH04! == -99

else float( !PRCHSCH13! )- !PRCHSCH04!

Any advice as to where the error is here?

0 Kudos