[GIS] Uisng Python Parser of Field Calculator with ArcPy

arcgis-10.2arcpyfield-calculatorpython-parser

I have a point shapefile with two columns i want to process.
The first column is aspect and the second is aspect_m60, there is only one row with the aspect of my point. I have tried to write a script in Python for ArcGIS 10.2.2 because i want to put it in my code but with no success.
The code is this:

# Calculate Field
import arcpy
# Set environment settings
arcpy.env.workspace = "c:/W/Sik"
# Set local variables
inTable = "Point"
fieldName = "aspect_m60"
expression = "getCalc(!aspect!, !aspect_m60!)"
codeblock = """def getCalc(aspect, aspect_m60):
   if (aspect < 60):
      aspect_m60 = (aspect - 60) + 360
   if (aspect = 60):
      aspect_m60 = aspect - 60
   else:
      aspect_m60 = aspect - 60"""

Best Answer

It is much more intuitive, in my opinion, to work with Cursors (rather than trying to emulate the field calculator in a script) for this type of problem. This is how you would port the problem over to an Update Cursor:

import arcpy

# The input FC
fc = "C:/W/Sik.gdb/yourFC"

with arcpy.da.UpdateCursor(fc, ["aspect", "aspect_m60"]) as cursor:
    for row in cursor:
        # row[0] = "aspect"
        # row[1] = "aspect_m60"
        if row[0] < 60:
            row[1] = (row[0] - 60) + 360
        elif row[0] == 60:
            row[1] = row[0] - 60
        else:
            row[1] = row[0] - 60

        cursor.updateRow(row)
Related Question