Calculate Field in Python

1109
3
Jump to solution
07-27-2021 10:32 AM
KirstenDuncan
New Contributor

Hello!
I'm dabbling back into python and scripting (it's been about 7 years since I last wrote scripts) and I'm trying to create a script tool to help with some of my property data updates that I do as part of my workload, I typically do all of this manually, so this tool will greatly cut down the time it takes to do this task.

I'm getting hung up on the Calculate Field function and I'm hoping you all can help me:

My shapefile has three fields ('USER_FNAME', 'USER_LNAME' and 'USER_CORPN') that I'm pulling information from to populate a new field: 'NAME'.  I want the script to first-off populate NAME with !USER_LNAME! + " " + !USER_FNAME! (easy, done...) but then, I would like to then select all values that are blank (or " ") in the NAME field and calculate the selected records to populate NAME with !USER_CORPN!. This way, it doesn't overwrite the !USER_LNAME! + " " + !USER_FNAME! statement. 

I feel like I possibly need an if/else statement or something in the code block but I'm getting lost in all the arc help documents lol. 

0 Kudos
1 Solution

Accepted Solutions
Tim_McGinnes
Occasional Contributor III

Something like the following should do it all in one step. It is only checking that the first name and last name have empty strings, not that they are null, so you may need to modify the if statement to match your data.

 

expression = "getName(!USER_FNAME!,!USER_LNAME!,!USER_CORPN!)"

codeblock = """
def getName(fname, lname, corpn):
    if fname=="" and lname=="":
        return corpn
    else:
        return fname + " " + lname
"""

arcpy.CalculateField_management(<table>, "NAME", expression, "PYTHON3",  codeblock)

 

Another way to do this would be with an update cursor.

View solution in original post

3 Replies
Tim_McGinnes
Occasional Contributor III

Something like the following should do it all in one step. It is only checking that the first name and last name have empty strings, not that they are null, so you may need to modify the if statement to match your data.

 

expression = "getName(!USER_FNAME!,!USER_LNAME!,!USER_CORPN!)"

codeblock = """
def getName(fname, lname, corpn):
    if fname=="" and lname=="":
        return corpn
    else:
        return fname + " " + lname
"""

arcpy.CalculateField_management(<table>, "NAME", expression, "PYTHON3",  codeblock)

 

Another way to do this would be with an update cursor.

KirstenDuncan
New Contributor

This is excellent and exactly what I needed!! Thank you so so much!! 😊

0 Kudos
Bud
by
Notable Contributor

In my opinion, field calculation IF statements are unnecessarily cumbersome. I proposed a new kind of mechanism here: Idea - Virtual Attributes (ad hoc)

0 Kudos