By Adam Reed


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

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"""

1 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

Related Questions

Sponsored Content

1 Answered Questions

2 Answered Questions

[SOLVED] Using cursor to delete rows with <Null> values in table using ArcPy?

  • 2018-11-13 19:50:55
  • Kaitlyn
  • 85 View
  • 0 Score
  • 2 Answer
  • Tags:   arcpy cursor null

1 Answered Questions

3 Answered Questions

1 Answered Questions

[SOLVED] ArcMap Field Calculator Remove Null values

2 Answered Questions

1 Answered Questions

[SOLVED] Using Null values in Field Calculator

1 Answered Questions

[SOLVED] Using ArcPy update cursor to replace <Null> value?

Sponsored Content