First off, I would reccomend using a with
statement when implementing your cursors. The with
statement will automatically close your cursor when the code exits the code block, freeing up the resources used by the cursor. as to exactly how you calculate the area into hectares will depend on the units the shapefile is currently in. In the code below, I have assumed that your shapefile is in meters.
import arcpy
shapefile = "path/shapefile"
CODE_TEST = "2022"
# Add CODE field
arcpy.AddField_management(shapefile, "CODE", "TEXT", 10, "", "", "refcode", "NULLABLE", "REQUIRED")
# Update CODE field with CODE_TEST value
with arcpy.da.UpdateCursor(shapefile, ["CODE"]) as cur:
for row in cur:
row[0] = CODE_TEST
cur.updateRow(row)
# Add SUP_HA field
arcpy.AddField_management(shapefile, "SUP_HA", "DOUBLE", 10, 2, "", "refcode", "NULLABLE", "REQUIRED")
# Calculate area in hectares and update SUP_HA field
with arcpy.da.UpdateCursor(shapefile, ["SHAPE", "SUP_HA"]) as cur:
for row in cur:
# Get geometry of shapefile
geom = row[0]
# Calculate area in hectares
area_ha = geom.area / 10000 # 1 hectare is equal to 10000 square meters. Change the calculation in this line if geom.area is not in square meters
# Update SUP_HA field with calculated area
row[1] = area_ha
cur.updateRow(row)
The second cursor will access the geometry of your shapefile in the units it currently is in, and calculate the conversion in to hectares (again, assuming the area is in square meters)
arcpy.UpdateCursor
-- Only usearcpy.da.UpdateCursor
. 2. Calculate Field and Calculate Geometry Attributes are going to be much faster than a cursor on a large table. 3. "path/shapefile" isn't a valid shapefile path, but "path/shapefile.shp" is.