I am working in ArcSDE geodatabase where I have a feature class 'Mange_Waste' and "Q1", "Q2" are two fields. I wanted to use Python script for populating "Q2" from "Q1" with a condition. Like, if the value in "Q1" is "a", then it should return "1" in "Q2". I have hundreds of records in "Q1".
I am using following code however, it's giving me syntax error.
If Q1 == "a":
Q2 = 1
else :
Q2 = 0
What am I doing wrong?
3 Answers 3
you need to use a block or to write everything in a single line (respecting the indentations)
block (with Python parser)
def myfunction(a,b):
if a == 'a':
return 1
else:
return 0
then you call the function defined in your block
myfunction(!Q1!, !Q2!)
note that this is a general solution, but in your specific case you could simply use
!Q1!=='a'
in the field calculator (with Python parser). The boolean true/false will be 1/0 in an integer field.
Since you tagged this with python, you can also accomplish this with an updatecursor. Using field calculator in python for multiline statements is sometimes more difficult than the same function in a cursor.
with arcpy.da.UpdateCursor("Mange_Waste", ("Q1", "Q2")) as cursor:
for row in cursor:
if row[0] == "a":
row[1] = 1
else:
row[1] = 0
cursor.updateRow(row)
Alternatively:
with arcpy.da.UpdateCursor("Mange_Waste", ("Q1", "Q2")) as cursor:
for row in cursor:
row[1] = 1 if row[0] == "a" else 0
cursor.updateRow(row)
Your logic is correct. This help guide may help you out in the future for using python in the field calculator. There are already valid pythonic answers above I'll post another option, in VB (sometime's it is simplier than python).
In field calculator choose "show codeblock" for "Q2" under "Pre-logic script code" write:
In VB:
if [Q1] = "a" then
result = "1"
else
result = "0"
end if
Under Q2 = write:
result
Explore related questions
See similar questions with these tags.