3

I'm using ArcGIS 10.1. I want to use the calculate field tool in ModelBuilder on a table where if field1 is null, it should take the value of field2. If field1 has a value then it should stay as is.

4

This should do it ...

Parser: Python

Pre-Logic Script Code:

def FixNull(Field1,Field2):
  if Field1 is None or Field1.strip() == "":
    return Field2
  else:
    return Field1

Field1 =

FixNull(!Field1!, !Field2!)
  • 1
    Simpler if statement: if Field1 is None or Field1.strip() == "" – nmpeterson Feb 7 '14 at 22:16
  • +1 but for now I have left my Answer as is because I do not know how asker wants to handle values with trailing spaces e.g. should "AB " be left alone (my code) or converted to "AB" (yours) – PolyGeo Feb 7 '14 at 23:26
  • 1
    It wouldn't be returning that value, though. It's just evaluated for the test to return Field2 for any null or whitespace-only values. – nmpeterson Feb 8 '14 at 0:51
  • +1 Now I understand and have updated my Answer - thanks for your patience :-) – PolyGeo Feb 8 '14 at 0:59
  • @PolyGeo hey, When i use the if statement it breaks when finding a none true with the error 'NoneType' object has no attribute 'strip' so I had to split it into two if's. Am I missing something? – Barrett Feb 3 '16 at 19:27
1

Null is a special value, doesn't use the = sign. You use the Is keyword. You need to test if Field1 Is Null. Probably the simplest way is to just select all records where Field1 Is Null, then calculate those to Field2.

1

The Update Cursors in arcpy both (da.UpdateCursor10.1, UpdateCursor10.1) have a spot for a SQL clause ("fieldX IS NULL" or "fieldX == """) to limit the extent of records updated.
If there are other updates to be done, the records can be tested to check if they are null (if x is None:)

import arcpy

fc = "\\...\\X.gdb\\your_feature_class"
fields = ["field1", "field2"]
#field1 is row[0]; field2 is row[1]

#example 1 with sql
rows = arcpy.da.SearchCursor(fc, fields, "", "", "field1 IS NULL")
# clause may be "field1 = """ if it's a blank text field
for row in rows:
    row[0] = row[1]
    rows.updateRow(row)
del rows

#example 2 without sql clause
rows = arcpy.da.SearchCursor(fc, fields)
for row in rows:
    if row[0] is None:
    # if row[0] == ""
            row[0] = row[1]
            rows.updateRow(row)
del rows
  • @Me...Every time I see field calculator my mind goes straight to cursors (preference). So here's my answer using UpdateCursor. – gm70560 Dec 21 '13 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.