Python Calculate Field If Statement

10464
14
02-14-2011 10:57 AM
Ryan_Galbraith
New Contributor III
Just wondering if the Python-Geoprocessing Community could help me.  I am trying to write the following code block into a calculate field called weight from the values in another field called Symbol.

def Reclass( !Weight!):
  if ( !SYMBOL! == 6):
    return 1.2
  elif ( !SYMBOL! == 85):
    return 1.5
  elif ( !SYMBOL! ==2):
    return 1
  elif ( !SYMBOL! ==42):
    return 1.8
  elif ( !SYMBOL! ==58):
    return 2

It just won't work.  help...
0 Kudos
14 Replies
by Anonymous User
Not applicable
Original User: niklas.norrthon

I tested it and got the same error, and I still don't understand why. But I found an easy workaround: Rename the dictionary to something else (without underscore) like symweights. Do that both in the code block and the expression field and it works.
0 Kudos
Ryan_Galbraith
New Contributor III
I tested it and got the same error, and I still don't understand why. But I found an easy workaround: Rename the dictionary to something else (without underscore) like symweights. Do that both in the code block and the expression field and it works.


That works perfect.  Like Python should!  Amazing.  I choose this method, because I wanted to use the ModelBuilder.  Not sure if a cursor would work in this case.
0 Kudos
by Anonymous User
Not applicable
Original User: niklas.norrthon

That works perfect.  Like Python should!  Amazing.  I choose this method, because I wanted to use the ModelBuilder.  Not sure if a cursor would work in this case.


A cursor would work just as well (untested):

symbol_weights = {
    6: 1.2,
    85: 1.5,
    2: 1.0,
    42: 1.8,
    58: 2.0,
    }

cur = arcpy.UpdateCursor(my_feature_class)
for row in cur:
    row.Weight = symbol_weights[row.SYMBOL]
    cur.UpdateRow(row)
0 Kudos
Ryan_Galbraith
New Contributor III
Cursor works better!
0 Kudos
AndyOmmen
Esri Contributor

Hi Ryan,

When you define the method within the Python codeblock, use a variable for the Reclass method's parameter and use that variable within the method's logic:

def Reclass(weight):

  if (weight == 6):

    return 1.2

  elif (weight == 85):

    return 85

.....

Then when you call the Reclass method in the Calculate Field Expression parameter, you will then pass in the SYMBOL field:

Reclass(!SYMBOL!)