I’m trying label up a blank field with ‘yes’ or ‘no’ to the presence of names with either the word ‘Estuary’, ‘Loch’, or ‘Firth’ using * as a wildcard, in Field Calculator. I think I'm getting mixed up with SQL here... can anyone help?

The example of code I've used is:

arcpy.AddField_management(workingPath + "/GB_Catchment_merge.shp", "Offshore", "TEXT", "", "", 3)

expression = "LookUp( !MNCAT_NAME! )"
code_block = "def LookUp( a ):\n\

  if ( a == '*Estuary*' ):\n\

    return 'yes'\n\

  elif ( a == '*Loch*' ):\n\

    return 'yes'\n\

  elif ( a == '*Firth*.' ):\n\

    return 'yes'\n\


    return 'no'"

arcpy.CalculateField_management(workingPath + "/GB_Catchment_merge.shp", "Offshore", expression, "PYTHON", code_block)
  • Do you want to use Calculate Field or are you ok with da.UpdateCursor instead? – BERA May 8 '19 at 12:57
  • I have been using Field Calculator? – Cheekychives May 8 '19 at 12:58
  • Have you tried LIKE instead of == ? – Bill Chappell May 8 '19 at 13:05
  • Hi, I've just tried LIKE and it doesn't like it. – Cheekychives May 8 '19 at 13:43

I recommend using da.UpdateCursor instead of calculate field. The syntax is easier and unless you have many thousands of rows, the speed will match calculate field. You can try:

import arcpy, os

fc = os.path.join(workingPath,"GB_Catchment_merge.shp")
fields = ['MNCAT_NAME','Offshore']
yesses = ['Estuary','Loch','Firth']

with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        if any([yes in row[0] for yes in yesses]): #row[0] is first field in fields list = MNCAT_NAME
            row[1] = 'yes'
            row[1] = 'no'
  • 1
    Brilliant! It worked. Thank You! – Cheekychives May 8 '19 at 13:46

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.