More

Uisng Python Parser of Field Calculator with ArcPy?


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"""

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)

You are trying to set the field within the code block, when actually you need the code block toreturnthe value you're looking for. If you just just addreturn aspect_m60after the else block, it should work fine.

Think of the code block as a place to write functions whose results can be used in your field calculator expression.


Your function is not returning anything. I've modified your code to return the value of aspect_m60.

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

As a couple others have pointed out, you're missing a return value. You're also confusing the assignment operator=for an equality operator==(in the 2nd if). The if structure is also incorrect (if/if/else), and will calculate the wrong value for anything less than 60 (should be if/elif/else).

If you still want to use CalculateField (the other answer with UpdateCursor is perfectly valid), the code block below would be what you intended.

codeblock = """def getCalc(aspect, aspect_m60): if aspect < 60: aspect_m60 = (aspect - 60) + 360 elif aspect == 60: aspect_m60 = aspect - 60 else: aspect_m60 = aspect - 60 return aspect_m60 """


Watch the video: 1 Basic Arcmap Field Calculations Using Python (October 2021).