3

I've been trying to take the X and Y coordinates of the true centroid from a polygon shapefile I have called HamDA.shp and add such coordinates to two float fields called X and Y (with 12 precision and 2 scale) that exist within HamDA.shp.

I know I need to use an Update Cursor to accomplish this task, but i'm not entirely sure how to set it up properly.

Here's what I have so far:

import arcpy
arcpy.env.workspace = "C:/Users/Alex/SampleData"
fc = "HamDA.shp" 

vertexarray = arcpy.Array()
with arcpy.da.UpdateCursor(fc,["SHAPE@"]) as cursor:
    for row in cursor:
        for vertex in row[0]:
            vertexarray.add(vertex.X,vertex.Y)
            cursor.updateRow(vertexarray)
2

You can also just use the Add Geometry Attributes tool.

You have the choice to add CENTROID or CENTROID_INSIDE coordinates.

If you really want to use a cursor, you need to use the SHAPE@TRUECENTROID token, it returns a tuple with X, Y coordinates. Then call the X and Y by their index:

with arcpy.da.SearchCursor(fc, "SHAPE@TRUECENTROID") as cur:
    for row in cur:
        print """X = {}, Y = {}""".format(row[0][0], row[0][1])
1

I'm not sure what you mean by true centroid but this will work on "normal" centroids. I use the SHAPE@X and SHAPE@Y tokens to get the centroid coordinates of each feature and then add these in two columns:

import arcpy

arcpy.env.workspace = "C:/Users/Alex/SampleData"
fc = "HamDA.shp"

arcpy.AddField_management(in_table='fc', field_name='CentroidX', field_type='DOUBLE')
arcpy.AddField_management(in_table='fc', field_name='CentroidY', field_type='DOUBLE')

with arcpy.da.UpdateCursor(fc,['SHAPE@X','SHAPE@Y','CentroidX','CentroidY']) as cursor:
    for row in cursor:
        row[2]=row[0]
        row[3]=row[1]
        cursor.updateRow(row)
1

Don't forget to delete row and cursor. Use Shape@XY and call x and y using their indexes. You can use x and y separately.

import arcpy
arcpy.env.workspace = "C:/Users/Alex/SampleData"
fc = "HamDA.shp" 

vertexarray = arcpy.Array()
with arcpy.da.UpdateCursor(fc,["SHAPE@XY","X","Y"]) as cursor:
    for row in cursor:
        row[1] = row[0][0]
        row[2]= row[0][1]
        cursor.updateRow(row)
del row
del cursor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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