By Adam Reed


2019-01-10 20:46:43 8 Comments

I feel like this might be a bit of a simple answer but I can't figure out how to 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"""

2 comments

@user2856 2019-01-10 22:15:05

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 with None 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

@MBuie 2019-01-10 22:12:12

I've confirmed all three of the following work when using the Field Calculator. Could it be an error somewhere else? Does the code work for the other condition?

if cond == None:
    return 1
if cond is None:
    return 2
if not cond:
    return 3

Related Questions

Sponsored Content

1 Answered Questions

1 Answered Questions

1 Answered Questions

[SOLVED] Allowing NULL value in field's value map in QGIS?

  • 2017-03-13 10:17:08
  • Martin Hügi
  • 601 View
  • 6 Score
  • 1 Answer
  • Tags:   qgis style null

1 Answered Questions

1 Answered Questions

0 Answered Questions

python label expression

1 Answered Questions

3 Answered Questions

[SOLVED] Label Expressions to replace null values with text not in feature class

  • 2011-10-14 09:44:15
  • jorp
  • 6593 View
  • 8 Score
  • 3 Answer
  • Tags:   arcmap labeling

Sponsored Content