Lau9 Lau9 - 1 month ago 14
Python Question

field calculator based on attribute values

I'm using ArcGIS 10.2.2 basic licence, trying to fill a column in an attribute table based on the following argument:

'If field1 is equal to field2, return field3, if not, return 'null''


Fields 1 and 2 are text, field 3 is numeric.

I've tried this code in the field calculator:

pre-logic script code block...

def calc(Score):
if ( !Field1! == !Field2!):
return !Field3!
else:
return 'null'

Score = calc(!Score!)


Im really new to coding, so Im really not sure if this even makes sense (sorry), but any help would be appreciated. Also, does anyone know if a good starting point to learn python specifically for ArcGIS?

There seem to be hundreds of tutorials but I can't find anything specifically for editing tables etc.

Answer Source

It seems that for the Python code block, you have to use the fields as function parameters, e.g.:

def score(f1, f2, f3):
  if ( f1 == f2):
    return f3
  else:
    return None

Expression: score(!Field1!, !Field2!, !Field3!)

Whereas for a VB Script code block you can do this:

Dim score
  if ( [Field1]== [Field2]) then
    score = [Field3]
  else
    score = vbnull
  end if

Expression: score

Note that a field value can only be set to null if the field is nullable.