Select to view content in your preferred language

Using a code block to Calculate Field

703
2
10-08-2013 11:58 AM
MargaretWooten
Emerging Contributor
Hi. I'm trying to do something simple in Arc but with no luck and was hoping someone could point out my error.

I want to use the value of pixels (Value field) in a raster to define a new field called 'TreeClass', where 6 classes will be represented.

I built the attribute table and added the field (tried both short integer and long integer, the latter which matches the Value field type).

I use the following in the Code Block parameter for the Calculate Field tool:
def getclass(Value):
 if Value >= 0 & Value <= 10:
  return 1
 if Value >= 11 &  Value <=20:
  return 2
 if Value >= 21 & Value <= 40:
  return 3
 if Value >= 41 & Value <=60:
  return 4
 if Value >= 61 & Value <=100:
  return 5
 else:
  return 6


And enter "getclass(!Value!)" into the Expression parameter.

When I run the tool, the TreeClass field populates with 1's.

What am I doing wrong here? Any advice would be greatly appreciated. Thank you!
Tags (2)
0 Kudos
2 Replies
MathewCoyle
Honored Contributor
& is used in VB usually, in python is has a different function that you are probably not interested in.

Try this instead.
def getclass(Value):
 if Value >= 0 and Value <= 10:
  return 1
 elif Value >= 11 and  Value <=20:
  return 2
 elif Value >= 21 and Value <= 40:
  return 3
 elif Value >= 41 and Value <=60:
  return 4
 elif Value >= 61 and Value <=100:
  return 5
 else:
  return 6


You could also shorten it using this format.

def getclass(Value):
 if 0 <= Value <= 10:
  return 1
 elif 10 < Value <= 20:
  return 2
 elif 20 < Value <= 30:
  return 3
 elif 30 < Value <= 60:
  return 4
 elif 60 < Value <= 100:
  return 5
 else:
  return 6
0 Kudos
MargaretWooten
Emerging Contributor
Thanks Matthew! Looks like I've been away from python for too long.
0 Kudos