TransWikia.com

Re-ordering text strings within field using Python Parser of Field Calculator

Geographic Information Systems Asked on August 11, 2021

At ArcGIS 10.8.1, I have a shapefile attribute table containing a text field with names ordered last, first, middle, as in this example:

Smith Sally J
Doe John
Jones William Randolph

I need to reorder the names so that they are listed as first, middle, last:

Sally J Smith
John Doe
William Randolph Jones

I think that moving the first text string (i.e. the last name) to the end would solve the problem.

I’ve attempted to reorder the names into a second, empty text field using the Field Calculator, without success. In particular, I’ve looked into the Python .split() function, but am stymied with how to move the first text string to the end.

One Answer

You try the following code in the codeblock of Field Calculator:

def sort_name(n):
    split = n.split()
    if len(split) == 0:
        return ''
    elif len(split) < 3:
        return ('{0} {1}').format(split[1], split[0])
    else:
        return ('{0} {1} {2}').format(split[1], split[2], split[0])

enter image description here

The code split the text in the field and create a list of names. If the names in the source field is empty len(split) == 0, it will return empty string. If the length of the list is less than three as the case in John Doe it will rearrange the text taking into consideration only two names. Otherwise it will rearrange the three names in the source field name.

Here is the result:

enter image description here

Answered by ahmadhanb on August 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP