ArcPy Field Calculation within Loop

6036
5
Jump to solution
03-31-2016 07:32 AM
PatrickMcKinney1
Occasional Contributor III

I am writing an ArcPy script that will run from a tool with user inputs.  The user will select an input layer and output name/directory.  I have my current code below.  The tool will then do the following:

  1. Loop through each record in the input layer and do the following within each loop cycle:
    1. clip a census blocks layer by the input feature
    2. Create a field in the output clip layer to hold an area ratio value
    3. Create a field in the output clip layer to hold an estimated population value
    4. Perform a field calculation between two fields in the output clip layer to produce the area ratio (new area divided into original area)
    5. Perform a field calculation bewteen two fields in the output clip layer to produce the estimated population (area ratio value calculated in #4 mulitplied by the population field)

Let's say the input layer contains three records (1500-ft, 2000-ft, and 2500-ft).  There would be three output layers that are clipped census block layers based upon the records from the input, each with estimated census populations based upon the distances from the input feature.  The layers would have names like Output_ft_1500, Output_ft_2000, and Output_ft_2500.

My code can do everything except complete the field calculations.  I'm not sure if I'm missing something simple with the syntax for a SQL expression using fields or what.

Please let me know if you have any questions. I tried to explain things as best as I could.

Here is the error I get:

Traceback (most recent call last):

  File "F:\Scripts\ArcGIS Geoprocessing\SARA Tool\EstimateCensusPopulation.py", line 73, in <module>

    fieldExpression = newArea / orgArea

TypeError: unsupported operand type(s) for /: 'Field' and 'Field'

Failed to execute (EstimateCensusPopulation).

----------------

# Import arcpy
import arcpy

#Set workspace

# Sara Facility
sara = arcpy.GetParameterAsText(0)

# Clip Feature - U.S. Census Blocks
censusBlocks = r'\\CCPASR07\ncgs$\Scripts\ArcGIS Geoprocessing\SARA Tool\SARA_Tool_DEV.gdb\CensusBlocks_2010'

# Output
output = arcpy.GetParameterAsText(1)


# Search cursor
cursor = arcpy.SearchCursor(sara)

for row in cursor:
  
    # Clip features
    feat = row.Shape
  
    # Append buffer distance and units to name
    # Buffer distance
    buffDist = str(int(row.BUFFDIST))
  
    # Buffer units to name
    buffUnits = row.UNITS
  
    # Appended output name variable
    buffAppend = '_' + buffUnits + '_' + buffDist


    # Execute clip tool on each row
    newInput = arcpy.Clip_analysis(censusBlocks, feat, output + buffAppend)

    # Add message that Clip is completed
    arcpy.AddMessage('Feature Clip operation completed')

    # Add field to hold clip area to original area ratio
    areaRatioFieldName = 'AREARATIO'
    areaRatioFieldType = 'DOUBLE'
    # Execut tool
    arcpy.AddField_management(newInput, areaRatioFieldName, areaRatioFieldType)

    # Add message that Area Ratio Field has been added
    arcpy.AddMessage('Area Ratio field added')

    # Add field to hold estimated population
    estPopFieldName = 'ESTPOP'
    estPopFieldType = 'LONG'
    # Execut tool
    arcpy.AddField_management(newInput, estPopFieldName, estPopFieldType)

    # Add message that Estimated Population Field has been added
    arcpy.AddMessage('Estimated Population field added')

    ### Code does not work after this point ###
    areaInField = arcpy.ListFields(newInput, 'AREARATIO')[0]
    newArea = arcpy.ListFields(newInput, 'Shape_Area')[0]
    orgArea = arcpy.ListFields(newInput, 'ORAREA')[0]
    fieldExpression = newArea / orgArea
    arcpy.CalculateField_management(newInput, areaInField, fieldExpression, 'PYTHON_9.3')

del cursor
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

Your expression needs to be a string representation of your expression.  In Line 63 above, you are not trying to create an expression but divide two Field data types, which isn't supported.  Also, be careful when building your expression that you use field names and not field objects.

Try replacing Lines 60-64 with:

fieldExpression = '!Shape_Area! / !ORAREA!'
arcpy.CalculateField_management(newInput, 'AREARATIO', fieldExpression, 'PYTHON_9.3') 

View solution in original post

5 Replies
AdrianWelsh
MVP Honored Contributor

Hi Patrick,

Consider blocking your code properly in the thread to make it easier to read:

Use Advanced Editor > double arrows > syntax > python

PythonSyntaxGeoNet.PNG

Also, consider using arcpy.da.SearchCursor instead of arcpy.SearchCursor as the "da" method is newer and faster.

Where is the code throwing an error? Do you get an error message?

0 Kudos
PatrickMcKinney1
Occasional Contributor III

Traceback (most recent call last):

  File "F:\Scripts\ArcGIS Geoprocessing\SARA Tool\EstimateCensusPopulation.py", line 73, in <module>

    fieldExpression = newArea / orgArea

TypeError: unsupported operand type(s) for /: 'Field' and 'Field'

Failed to execute (EstimateCensusPopulation).

0 Kudos
AdrianWelsh
MVP Honored Contributor

Hmmm, at this point, I would put in some print statements for debugging to see what is actually being returned by "newArea" and "orgArea" to make sure they are valid and to make sure it is what you expected. Is it certain that those two are numbers and that they are divisible with each other?

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Your expression needs to be a string representation of your expression.  In Line 63 above, you are not trying to create an expression but divide two Field data types, which isn't supported.  Also, be careful when building your expression that you use field names and not field objects.

Try replacing Lines 60-64 with:

fieldExpression = '!Shape_Area! / !ORAREA!'
arcpy.CalculateField_management(newInput, 'AREARATIO', fieldExpression, 'PYTHON_9.3') 
PatrickMcKinney1
Occasional Contributor III

Joshua,

Thanks! That fixed the problem.  I guess it was something simple after all.

0 Kudos