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
-
1Are the Text fields actually Null, or just empty, i.e. '' ?recurvata– recurvata2016年06月17日 14:30:41 +00:00Commented Jun 17, 2016 at 14:30
-
Text fields are empty ''Josh J– Josh J2016年06月20日 09:50:11 +00:00Commented Jun 20, 2016 at 9:50
2 Answers 2
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– GeoJohn2016年06月17日 14:37:23 +00:00Commented Jun 17, 2016 at 14:37
-
2A simpler way would just be
if Text1:
-- BothNone
and empty strings''
are false-y values in Python.Paul– Paul2016年06月17日 21:15:51 +00:00Commented Jun 17, 2016 at 21:15 -
I've tried all of the options mentioned and they return
Text1
but notText2
orText3
. This is the same whether I useNone
or''
and!=
orif Text1:
. Is this a job that field calculator can't handle and should I switch to arcpy instead?Josh J– Josh J2016年06月20日 10:00:33 +00:00Commented Jun 20, 2016 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– recurvata2016年06月21日 13:27:50 +00:00Commented Jun 21, 2016 at 13:27
-
Fixed. Using this post gis.stackexchange.com/questions/81143/…Josh J– Josh J2016年07月04日 10:52:22 +00:00Commented Jul 4, 2016 at 10:52
You need to make sure you're passing the other fields in the function call at the bottom. getClass(!Field1!, !Field2, !Field3!)
Explore related questions
See similar questions with these tags.