3

我有一个带有多边形的 shapefile。我想找到每个的质心并将它们的 xy 坐标放入字段EastingNorthing. 我能够找到eastingand northing,但我无法将它放入属性表(它显示为空)。

import arcpy
arcpy.env.workspace = folderpath
arcpy.env.overwriteOutput = True

inputRoofs = "Roof"

print "working"


table = inputRoofs

arcpy.AddField_management(inputRoofs, 'Easting', 'DOUBLE')

arcpy.AddField_management(inputRoofs, 'Northing', 'DOUBLE')


print "fields added"

roofList_x = []

roofList_y = []

roof_cursor = arcpy.UpdateCursor("Roof")
for roof in roof_cursor:
    roof_geom = roof.Shape
    roofList_x.append(roof_geom.centroid.X)
    roofList_y.append(roof_geom.centroid.Y)

print roofList_x
print roofList_y
print "done"
4

1 回答 1

3

这是一种使用CalculateField将质心值分配给新字段的实现。

# Name: CalculateField_Centroids.py
# Description: Use CalculateField to assign centroid values to new fields


# Import system modules
import arcpy
from arcpy import env

try: 
    # Set environment settings
    env.workspace = "C:/data/airport.gdb"

    # Set local variables
    inFeatures = "parcels"
    fieldName1 = "xCentroid"
    fieldName2 = "yCentroid"
    fieldPrecision = 18
    fieldScale = 11
    # Expressions are calculated using the Shape Field's geometry property
    expression1 = "float(!SHAPE.CENTROID!.split()[0])"
    expression2 = "float(!SHAPE.CENTROID!.split()[1])"

    # Execute AddField
    arcpy.AddField_management(inFeatures, fieldName1, "DOUBLE", 
                              fieldPrecision, fieldScale)
    arcpy.AddField_management(inFeatures, fieldName2, "DOUBLE", 
                              fieldPrecision, fieldScale)

    # Execute CalculateField 
    arcpy.CalculateField_management(inFeatures, fieldName1, expression1,
                                    "PYTHON")
    arcpy.CalculateField_management(inFeatures, fieldName2, expression2,
                                    "PYTHON")
except Exception, e:
    # If an error occurred, print line number and error message
    import traceback, sys
    tb = sys.exc_info()[2]
    print "Line %i" % tb.tb_lineno
    print e.message
于 2013-07-12T03:08:28.257 回答