I am trying to populate a field with a sorting code that represents the value of another field. Example:

 S4DNN2 |3.5
 H2BNN2  5.0

EXPCODE is a field with a value like "S4DNN2." SORT is a field that needs to represent the EXPCODE with a numerical value. What would I use for Python code to automatically populate the SORT field? I started with a simple "if" statement, but can't quite figure it out.

def EXPCODE(field_value):

    if field_value = "S4DNN2"
        return field_value "3.5"

    if field_value = "H2BNN2"
        return field_value "5.0"

The EXPCODE values I show are examples, I have about 67 different ones with unique numerical values that need to be populated in "SORT"

Any ideas?

Update: I am trying to execute this with the field calculator with use of the python parser

  • Would you be able to edit your question to make clear whether you are trying to do this using the Python parser of the Field Calculator in ArcGIS for Desktop, please? There are many Q&As here about this topic so I suspect your question will be a duplicate of one or more of them. – PolyGeo Apr 10 '15 at 23:39

In your code:

def EXPCODE(field_value):

    if field_value = "S4DNN2"
        return field_value "3.5"

    if field_value = "H2BNN2"
        return field_value "5.0"

should probably be:

def EXPCODE(field_value):   
    if field_value == "S4DNN2":
        return 3.5  
    elif field_value == "H2BNN2":
        return 5.0

but if this is coming from the Field Calculator there may be more details that you need to provide before this will work for you.

  • I tried your solution, but didn't have any success, just a syntax error in the results window. I read another post where you suggested to someone that they import there shapefile into a geodatabase for better results. I tried this also without any help. Any more ideas? Not sure what I'm doing wrong. – UpNorthGeek Apr 12 '15 at 2:09
  • Just a thought, the EXPCODE field is a text string while SORT is a double, would that make a difference? – UpNorthGeek Apr 12 '15 at 2:13
  • Could you edit your question to include the exact code you ran with the precise syntax error that you received, please? – PolyGeo Apr 12 '15 at 2:25
  • If these values are being returned to a field which is a Double then the quotes should not be included. I'll try to update my answer when I am on my laptop rather than iPhone. – PolyGeo Apr 12 '15 at 2:28
  • The code I ran was exactly how you suggested, both with and without quotes: def EXPCODE(field_value): if field_value == "S4DNN2": return "3.5" elif field_value == "H2BNN2": return "5.0" The error was "000539: Error message from Python. The calculation used by the Calculate Field or Calculate Value tool is invalid" – UpNorthGeek Apr 12 '15 at 3:40

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.