Learning Python ArcMap

390
4
11-21-2018 09:35 AM
RyanPhillips2
New Contributor

Hello! I am still in the learning stages of Python coding for ArcMap and have run into a bit of a snag. I am trying to calculate some fields based off of other fields in the attribute table. I am using the arcpy. CalculateField_management command and i'm not sure if I can throw an "IF",... "Then" statement  in there to calculate that field based off of another fields records. This is what I have, which is not working 

arcpy.CalculateField_management("SD_FP_Pro","SYM",
... if["FLD_ZONE] = "A","AE","AH","AO","VE" then "SYM" = "100"

I feel like I am combining two things that do not go together.

0 Kudos
4 Replies
curtvprice
MVP Esteemed Contributor

I generally only use Calculate Field in Python scripts if the expression is simple, like copying a field or assigning a field to a single value or expression.

If you have embedded if-then logic, I suggest using UpdateCursor:

with arcpy.da.UpdateCursor("SD_FP_PRO", ["SYM", "FLD_ZONE"]) as rows:
    for row in rows:
       if row[1] in ["A", "AE", "AH", "AO", "VE"]:
           row[0] = 100
           rows.updateRow(row)‍‍‍‍‍‍‍‍‍‍

UpdateCursor—Help | ArcGIS Desktop 

Now, if you are not in a python script and instead using the Calculate Field tool interactively or in Model Builder, a code block is your best bet:

# Calculate Field tool
# input table
SD_FP_PRO
# input field
SYM
# expression
f(!FLD_ZONE!)
# code block
def f(fz):
    if fz in ["A", "AE", "AH", "AO", "VE"]:
        return 100
    else:
        return fz‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Hope this helps you out.

RyanPhillips2
New Contributor

Thank you so much Mr. Price

0 Kudos
RyanPhillips2
New Contributor

Can I do the same thing for deleting rows based off of a certain field? 

>>> with arcpy.da.UpdateCursor("Export_Output",["ZONE_SUBTY"])as rows:
... for row in rows:
... if row in ["AREA OF MINIMAL FLOOD HAZARD"]
... row.deleteRow(row)

0 Kudos
curtvprice
MVP Esteemed Contributor

Perhaps, but the usual method of doing this task is to create a layer with Create Feature Layer, run a selection on it with Select Layer By Attributes, and then use the DeleteFeatures tool. (Or probably better, copy selected rows you want to a new dataset so you don't destroy data rows you may want later!)

Glad this helped!

May I share a little forum etiquette: a) please use a subject line that describes the content ("Python if then within field calculation") b) when you get a useful answer, mark it correct. These actions make the formum thread more useful for others in the community.