0

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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jul 14, 2014 at 16:32

3 Answers 3

5

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.

answered Jul 14, 2014 at 16:39
4

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)
answered Jul 14, 2014 at 16:50
0

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
answered Jul 14, 2014 at 17:11
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.