1

I'm trying to fill a blank field depending on the contents of three other fields using python in the field calculator.

Sample code is something like:

def getClass(Text1,Text2,Text3):
  if Text1 is None:
    return Text2
  elif Text2 is None:
    return Text3      
  else:
    return Text1

I can retrieve the value of the first field but never the 2nd two. I know this isn't the right way but I can't figure out the nesting levels... Any ideas?

UPDATE: Fixed by stripping out the white space. Credit to this post Using Calculate Field tool to calculate on null fields?

def getClass(Text1,Text2,Text3):
  if Text1.strip():
    x = Text1
  elif Text2.strip():
    x = Text2    
  elif Text3.strip():
    x = Text3
  else:
    x = "NA";
  return x
  • 1
    Are the Text fields actually Null, or just empty, i.e. '' ? – recurvata Jun 17 '16 at 14:30
  • Text fields are empty '' – user3725599 Jun 20 '16 at 9:50
1

Use the "not equal" operator for the field calculator.

def getClass(Text1,Text2,Text3):
  if Text1 != None:
    return Text1
  elif Text2 != None:
    return Text2      
  elif Text3 != None:
    return Text3
  else:
    return None;

You may also want to account for the possibility that none of the input fields have a value, as seen in the code snippet I posted.

Also, checkout this post about the difference between using the "is" operator versus "==":

https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python

  • @recurvata brings up a good point in the comment above. If you need to account for empty strings in place of <Null>, you could modify the boolean expressions like so ---> if Text1 != None and Text1 != "": – GeoJohn Jun 17 '16 at 14:37
  • 2
    A simpler way would just be if Text1: -- Both None and empty strings '' are false-y values in Python. – Paul Jun 17 '16 at 21:15
  • I've tried all of the options mentioned and they return Text1 but not Text2 or Text3. This is the same whether I use None or '' and != or if Text1:. Is this a job that field calculator can't handle and should I switch to arcpy instead? – user3725599 Jun 20 '16 at 10:00
  • Can't tell if you mean '' above or ' ' (an empty space) in your comment above. Empty space is likely incorrect. If no values are Null, testing for None won't help. '' or ' ' will always return Text1 in your code above, since '' and ' ' both != None; that is, your first test is always True, thereby returning Text1. Same with if Text1: – recurvata Jun 21 '16 at 13:27
  • Fixed. Using this post gis.stackexchange.com/questions/81143/… – user3725599 Jul 4 '16 at 10:52
0

You need to make sure you're passing the other fields in the function call at the bottom. getClass(!Field1!, !Field2, !Field3!)

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.