# Replicating the “Calculate Geometry” table tool in python

I'm trying to automate a very tedious process in our company that involves switching the data frame's coordinate system and performing calculate geometry on a couple of fields, these are the two situations I'm having trouble with :

First situation would be !SHAPE.CENTROID.X.! using data source's coordinate system with the unit conversion specified in the picture Second is switching the data frame coordinate system, choosing to use it and perform the following calculation : So, two main questions :

1) How to switch the data frame's coordinate system and calculate based on it

2) Get !SHAPE.CENTROID.X.! with the specified unit on picture 1

I'm using `arcpy.CalculateField_management` for this since there already is a selection

I really searched for this one but couldn't find what I'm looking for

• It's not quite clear what your broader context is. Do you have a list of feature classes that you need to calculate centroids for using two separate coordinate systems? Do you have a map within which you need to iterate over layers and calculate centroids using two separate coordinate systems? Do you have a series of maps within which you need to grab a single layer and calculate centroids...? The iteration is the challenge, but we don't know what you're iterating over. – Tom Jul 20 '16 at 19:09
• – Tom Jul 20 '16 at 19:11
• @Tom feature class containing points – Mojimi Jul 20 '16 at 19:13
• Since you have Points, I don't think you need Shape.Centroid.X just Shape.X. They might produce identical results. – klewis Jul 20 '16 at 20:14
• @Mojimi, so does it need to be repeated on the same feature class? Where is the "tedious" part coming in? – Tom Jul 20 '16 at 20:25

You can set the spatial reference of the data frame object in Python.

``````mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)
df.spatialReference = 31982 # SIRGAS_2000_UTM_Zone_22S
``````

However, I think it will be much more efficient to leave the data frame as is and just project the point geometry on the fly.

``````sr = arcpy.SpatialReference(31982) # SIRGAS_2000_UTM_Zone_22S
with arcpy.da.UpdateCursor(<layer_name>, ["SHAPE@", "X", "Y", "newX", "newY"]) as cursor:
for row in cursor:
newGeom = row.projectAs(sr)
row = row.centroid.X # current X
row = row.centroid.Y # current Y
row = newGeom.centroid.X # projected X
row = newGeom.centroid.Y # projected Y
cursor.updateRow(row)
``````

The Add Geometry Attributes tool will allow you to perform many of the functions found in the Calculate Geometry tool from within a model or Python script.

• Doesn't that add fields? They already exist, just need to update them – Mojimi Jul 20 '16 at 19:12
• Excellent, you can also define the Coordinate System inside the Add Geometry Attributes tool. – klewis Jul 20 '16 at 20:24