Avoiding Divide-by_Zero in Field Calculator in Model Builder

2622
1
08-24-2012 10:22 AM
EladMokadi
New Contributor
I'm having a problem when using the tool Calculate Field in Model Builder:
My calculation formula is [pop_per_pixel] = [POP_2010] / [RES_PIX] * [proportion].
Since some of the features have [RES_PIX]=0, the model stops and indicates an error. I tried to select only those features that aren't equal to zero, but the tool 'Select Layer By Attribute' could not be integrated in the model chain.
Is there a VB code I can put in the Code Block window?
What would be the Python code for that?
How else would you overcome this issue?

Thanks!
0 Kudos
1 Reply
curtvprice
MVP Esteemed Contributor
I tried to select only those features that aren't equal to zero, but the tool 'Select Layer By Attribute' could not be integrated in the model chain.


If you pass your dataset or table to Make Feature Layer or Make Table View with a where expression you should be able to connect its output to Calculate Field with just the rows you want available to calculate.

Alternatively, you could use a code block with Calculate Field. This would just give you nothing in the field if the divide failed for any reason:

expr:
f(!POP_2010!,!RES_PIX!)


Type: PYTHON

code:
def f(pop,res):
  try:
    return pop / float(res)
  except:
    pass