I am trying to do a simple if statement in ArcMap to calculate a new field. It takes the year that an attribute was rated from the "[RatingYear]" field and depending on that value, chooses the corresponding "[PASER<year>]" field value.
I want to learn more about Python coding, but can't get this to translate to Python. Is it possible to set a variable to a field value in Python?
Codeblock:
def reclass(RY,P20,P21):
if (RY == 2020):
return P20
elif (RY == 2021):
return P21
else:
return 0
Expression:
reclass(!RATINGYEAR!,!PASER2020!,!PASER2021!)
The syntax for fields is different, it uses ! instead of []. I find that it's better to call a function and pass the values into it so that I don't have to deal with the weird syntax in my own code, here is a snapshot for an example.
I called the variables var1 and var2 in the function and call the function in the expression below.
Translating your code would look something like this
def f(y, p2020, p2021):
if y == 2020:
return p2020
elif y == 2021:
return p2021
return 0
PASER_CLR =
f(!RATINGYEAR!, !PASER2020!, !PASER2021!)
It keeps what I am doing separate from the dataset then too in my mind it's less confusing.
if/elif/else are good constructs and I'll just add if you have a lot of values the if/elifs can get long and get hard to follow. To get around this, you can use a dictionary lookup.
def f(y, p2020, p2021):
fieldDict = {2020: p2020, 2021: p2021}
# gets the key (y) or returns 0 if there is no paring.
return fieldDict.get(y, 0)
PASER_CLR =
f(!RATINGYEAR!, !PASER2020!, !PASER2021!)