0

In ArcGIS 10.4.1, I am using the Python Parser of the Field Calculator. My Python knowledge is limited.

I would like to recalculate a field of strings that are separated by commas so that they are ordered numerically. Say I have "3, 2, 6, 4, 5, 1" and I would like it to be "1, 2, 3, 4, 5, 6".

Would it be possible to have a reverse sort?

I would like to apply the sorted values to new field, but I could also live with the sorted values in the original field.

2
  • Have you searched Stack Overflow for a Python code snippet that illustrates how to sort a string of comma separated values?
    – PolyGeo
    Apr 18, 2018 at 19:03
  • I haven't yet, but am looking now. Thanks for your edits and help.
    – Will S
    Apr 18, 2018 at 19:07

1 Answer 1

3

See this link for python code that does this with string values. To translate that to the Field Calculator and adjust it to deal with the spaces in your number list and to sort as integers numerically do the following Field Calculator settings:

Parser: Python

Code Block: Enabled

Pre-Logic Code Block:

def sortGroup(str):
    arr = str.split(', ')
    arr = sorted(arr, key=int)
    return ', '.join(str(i) for i in arr)

FieldYouAreCalculating: sortGroup(!FieldContainingNumberList!)

To reverse the sort change arr = sorted(arr, key=int) to arr = sorted(arr, key=int, reverse=True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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