2

Using Python, how do you add a new field to your shapefile and calculate the area in km2?

nmtoken
  • 13,355
  • 5
  • 38
  • 87
Julia
  • 31
  • 1
  • 3
  • Use arcpy.AddField_management(). For the area calculation, check out this question: http://gis.stackexchange.com/questions/57448/calculate-area-within-python-script-in-arcmap – Martin Mar 24 '14 at 15:48

3 Answers3

8

this is an example

import arcpy
from arcpy import env 
env.workspace = "D:/"
fc = "test.shp" 
arcpy.AddField_management(fc,"area","Double")
 expression1 = "{0}".format("!SHAPE.area@SQUAREKILOMETERS!")        
arcpy.CalculateField_management(fc, "area", expression1, "PYTHON", )
BBG_GIS
  • 5,825
  • 4
  • 45
  • 88
6
from osgeo import ogr

shapefile = "C:/StudyArea.shp"
driver = ogr.GetDriverByName("ESRI Shapefile")
dataSource = driver.Open(shapefile, 1)
layer = dataSource.GetLayer()
new_field = ogr.FieldDefn("Area", ogr.OFTInteger)
layer.CreateField(new_field)

for feature in layer:
    geom = feature.GetGeometryRef()
    area = geom.GetArea() * (0.000000092903)
    feature.SetField("Area", area)
    layer.SetFeature(feature)

dataSource = None

I assumed the coordinate system you're using is in US feet. If it's not, you'll need to change the area calculation.

ianbroad
  • 9,141
  • 4
  • 42
  • 88
3

You can use an Update Cursor and a shape area token SHAPE@AREA to make the calculations.

import arcpy, os

file = r'C:\temp\polygon.shp'
arcpy.AddField_management (file, "area", "FLOAT")

with arcpy.da.UpdateCursor(file, ["SHAPE@AREA", "area"]) as cursor:
    for row in cursor:
        row[1] = row[0] / 1E6 # if spatial reference in meters, convert to km
        cursor.updateRow(row)
Aaron
  • 51,658
  • 28
  • 154
  • 317