You learn something new every day in GIS.
If I open a shapefile attribute table, select an attribute, and use the field calculator to populate the field with an expression such as...
attributeX / 0
I get an error all calculated values were invalid, no rows were updated.
But
attributeX / attributeY returns no error even if values in attributeY have zero values, In fact, it populates those values with zero values.
This is disturbing.
If I do this same test in a geodatabase I get null values for the zero division rows.
I understand that there are data structure limitations. Shapefile fields are not nullable... but the shapefile example ought to give some warning!
Yes it is unfortunate that you have to keep track of the math you are performing to assess appropriate values. You can use a field name to reflect the situation ... AdivBor_0 ( col A divided by B or 0 if possible) or use a code block block and specify number as the output like by comparing 0.0 to a small number to yield an improbably large value
>>> a = 1 >>> b = 0.0 >>> small= 9.9e-99 >>> a/(max(b,small)) 1.0101010101010101e+98
also, confirm that the field does actually contain 0.0 and just doesn't look like zero because of field decimal point settings.
I am not a python expert, but I think you can add an "if" statement. So if the value of "attribute Y" was zero it will print "Error" in the field.
not in the field calculator, it needs to return a value to the field
So can't an "if" statement do the task somehow?
Tarek,
You could do the math using an arcpy cursor. Python would throw an error that you could catch. Still though, you would need to assign some value to the record in the shapefile that had a zero division error.
Another reason to use a geodatabase, I guess. At least you end up with a null value.
Oh.. I see! I am sorry I couldn't help! Using geodatabse, as you said, will at least give you null values.
Good Catch ....
This is why I like to stick with C or VB. I have confidence it will catch errors or inconsistencies such as you noted. In fact when I have to deal with Null values, I avoid python like a plague. I still have no confidence that it can trap and deal with null values. I still find situations where Python did not catch or trap (or more correctly I did not envision all the possibilities where a null value is described). I can'd give up isNull() ..... old, lazy and set my ways and now I have to worry about dividing by zero!
Good catch -- learned something else today.
actually it is not python that can't catch nulls...that is totally wrong. The problem lies in the fact that shapefiles aren't nullable which means that they have to have a value in the field. Python wouldn't have emerged as one of the preferred languages of choice for scientific computing if it couldn't catch division by zero.
ADDENDUM
If you want to read up on null and related issues in doing field calculations, have a read through
Before I forget ... # 18 ... Those pesky <null> things...