I've got code that pulls the center point from a layer, and places it in a new feature class as part of a more complex analytical process.
I'm trying to get the centroid written to an in_memory
feature class in order to use as a processing input for other stuff. There are no fields needed in addition to the SHAPE@XY
token. Here's what I've got:
def get_extent_centroid(layer):
desc = arcpy.Describe(layer)
if desc.dataType in ['FeatureLayer', 'RasterLayer']:
extent = desc.extent
array = arcpy.Array()
array.add(extent.lowerLeft)
array.add(extent.lowerRight)
array.add(extent.upperRight)
array.add(extent.upperLeft)
array.add(extent.lowerLeft)
pg = arcpy.Polygon(array)
centroid = pg.centroid
return centroid
inlyr = arcpy.GetParameter(0)
center = get_extent_centroid(inlyr)
center_fc = arcpy.management.CreateFeatureclass("in_memory", "layercenter", "POINT", spatial_reference=arcpy.Describe(inlyr).spatialReference)
with arcpy.da.InsertCursor(center_fc, 'SHAPE@XY') as cursor:
cursor.insertRow(center)
This results in:
TypeError: argument must be sequence of values
Which suggests that even though .centroid
yields a valid point geometry, I have to do something more with it before sending it to the SHAPE@XY
field?
1 Answer 1
So, apparently insertCursor
demands a list object. With the following, the code works. I'll leave it here for posterity; if mods want to remove the question in case they find it too basic, that's fine too.
def get_extent_centroid(layer):
desc = arcpy.Describe(layer)
if desc.dataType in ['FeatureLayer', 'RasterLayer']:
extent = desc.extent
array = arcpy.Array()
array.add(extent.lowerLeft)
array.add(extent.lowerRight)
array.add(extent.upperRight)
array.add(extent.upperLeft)
array.add(extent.lowerLeft)
pg = arcpy.Polygon(array)
centroid = pg.centroid
return centroid
inlyr = arcpy.GetParameter(0)
center = get_extent_centroid(inlyr)
center_fc = arcpy.management.CreateFeatureclass("in_memory", "layercenter", "POINT", spatial_reference=arcpy.Describe(inlyr).spatialReference)
# fixed part
center_row = [(center.Y, center.X)]
with arcpy.da.InsertCursor(center_fc, 'SHAPE@XY') as cursor:
cursor.insertRow(center_row)
-
1But first you ought to capture that SpatialReference in a variable, and pass it into the Polygon constructor. While optional, failure to pass in a spatial reference can corrupt your coordinates, and possibly the geometry itself, but only when it is rewritten to conform to the target SpatialReference, during the
insertRow
.Vince– Vince2021年04月24日 00:37:56 +00:00Commented Apr 24, 2021 at 0:37 -
Not that FeatureToPoint would do this faster.Vince– Vince2021年04月24日 14:57:38 +00:00Commented Apr 24, 2021 at 14:57
-
Accept your answer, one less unanswered questionBera– Bera2024年01月10日 08:21:46 +00:00Commented Jan 10, 2024 at 8:21