How do I refer to Null values in a field using an expression in Python?
I've tried using the following as well as = None and =Null but nothing has worked yet:
ScoreCondition = "Cond_Score(!"+Condition+"!)"
codeblock1 = """def Cond_Score(cond):
if cond > 90:
return 1
elif cond >= 71 and cond <= 90:
return 2
elif cond >= 51 and cond <= 70:
return 3
elif cond >= 20 and cond <= 50:
return 4
elif cond < 20:
return 5
elif cond is None:
return 1"""
Answer
Your problem is that in Python 2 None
is less than everything.
>>> None < 20
True
>>> None < numpy.nan
True
>>> None < float('-inf')
True
>>> None < 'Everything'
True
Notes:
- In ArcGIS Pro (Python 3) you'll get a
TypeError
using a numeric comparison operator withNone
which will help avoid this issue. - This doesn't apply to shapefiles as the old dBase format .dbf that stores the attribute table doesn't support null values
In your expression, Python is returning True
when evaluating the elif cond < 20
clause when cond
is really None
so never gets to the elif cond is None:
clause.
So the following will work because it tests for None
first:
def Cond_Score(cond):
if cond is None:
return 1
elif cond > 90:
return 1
elif cond >= 71 and cond <= 90:
return 2
elif cond >= 51 and cond <= 70:
return 3
elif cond >= 20 and cond <= 50:
return 4
elif cond < 20:
return 5
No comments:
Post a Comment