I am using ArcMap 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.
3 Answers
This should do it, and also deals with any empty or space-filled strings.
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!)
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.
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