2

I have two feature classes that are both parcels. They have a field for residential type with the values being either "Residential" or "Non-Residential". They also have another field for the shape area. I am trying to write a script with arcpy that will go through the feature classes and create a row in a new table that has the name, residential type, and the total area. I am having trouble with getting the code to select and add to the table to residential types. I am also trying to do this using cursors.

This is what I have so far

import arcpy
from arcpy import env
import os

env.overwriteOutput = 1
env.workspace = "C://Users//dylan//Downloads//Data5//Montgomery.gdb"

tab = "SummaryTable"
fcs = arcpy.ListFeatureClasses("*", "Polygon")

arcpy.CreateTable_management(env.workspace, tab)
arcpy.AddField_management(tab, "name", "string")
arcpy.AddField_management(tab, "restype", "string")
arcpy.AddField_management(tab, "area", "float")
tabcur = arcpy.da.InsertCursor(env.workspace + os.sep + tab, ["name","restype","area"])
3
  • 2
    I would use the Summary Statistics tool to do this in one line of code.
    – PolyGeo
    Commented Feb 2, 2023 at 20:15
  • The path to your workspace is not formatted correctly. pro.arcgis.com/en/pro-app/latest/arcpy/get-started/…
    – GBG
    Commented Feb 2, 2023 at 20:58
  • @GBG , That way isn't listed in the link you sent but the way I have it works correctly.
    – dwallis25
    Commented Feb 2, 2023 at 21:38

1 Answer 1

1

If you are insisting on using cursors, then one approach would be like this. Where there is a SearchCursor used to sum up the area field using a where clause to select just the residential type you require.

import arcpy
from arcpy import env
import os

def get_sum_field_value(in_table, field_name="OID@", where_clause=None):
    """Return the total value of a field in a table."""
    return sum(
        (r[0] for r in arcpy.da.SearchCursor(in_table, field_name, where_clause))
    )


env.overwriteOutput = True
env.workspace = "C:/Users/dylan/Downloads/Data5/Montgomery.gdb"

tab = "SummaryTable"
arcpy.CreateTable_management(env.workspace, tab)
arcpy.AddField_management(tab, "name", "string")
arcpy.AddField_management(tab, "restype", "string")
arcpy.AddField_management(tab, "area", "float")
tabcur = arcpy.da.InsertCursor(env.workspace + os.sep + tab, ["name","restype","area"])

fcs = arcpy.ListFeatureClasses("*", "Polygon")
for fc in fcs:
    res = get_sum_field_value(fc, field_name="area", where_clause ='restype= "Residential"')
    tabcur.insertRow((fc, "Residential", res))
    non_res = get_sum_field_value(fc, field_name="area", where_clause ='restype= "Non-Residential"')
    tabcur.insertRow((fc, "Non-Residential", non_res))
del tabcur

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.