# Find polygon centroid with Python

I'm using ArcGIS 9.3 to find centroid of some polygon features. I'd like to do this in Python, but so far I can only find solutions with VBA. Can anyone provide some leads here?

-
Do you need the centroid of each polygon, or the single centroid that would be from the combination of all the polygons? Also, what is your desired result? To have this as an attribute, or a variable to perform another operation, etc? There are a few ways to get the centroids, it just depends on why you need them as to what method to choose. – Get Spatial Jun 16 '12 at 20:06
Thanks for your response. i need to create centroid for each polygon. basically, i need to add centroid lat/lon to the output table. – Sweet n Sour Chicken Jun 18 '12 at 17:43

There are really two direct ways to pull the polygon centroids out using Python. The method you choose, depends solely on what your end usage is going to be.

If you simply want to use a python script to calculate fields that contain the polygon centroids, then you would use the following script. It is taken from this help document: Calculate Field (Data Management)

``````EXAMPLE 2:  PYTHON-based Calculation using geometry properties

# Calculate x and y centroid fields using the geometry property Centroid
import arcgisscripting, sys
gp = arcgisscripting.create()

inputFC = sys.argv[1]

# Centroid property returns a string with x and y separated by a space
xExpression = "float(!SHAPE.CENTROID!.split()[0])"
yExpression = "float(!SHAPE.CENTROID!.split()[1])"

gp.CalculateField_management(inputFC, "xCentroid", xExpression, "PYTHON")
gp.CalculateField_management(inputFC, "yCentroid", yExpression, "PYTHON")
``````

On the other hand, if you want access the centroid information for use later in a script, or for other operations, you will need to access the `geometry` object of each feature.

This script is adapted from this help topic on The geometry object

``````import arcgisscripting, sys
gp = arcgisscripting.create()

inputFC = sys.argv[1]

# Create search cursor
#
features = gp.SearchCursor(inputFC)

# Add each centroid coordinate pair to a list
#
centroidlist = []
xcoord = 0
ycoord = 0

for feat in features:
# Create the geometry object
#
geom = feat.shape
# Centroid property returns a string with x and y separated by a space
xcoord = geom.centroid.split()[0]
ycoord = geom.centroid.split()[1]

centroidlist.append((xcoord,ycoord))
``````
-
Thanks a lot! this is extremely helpful! – Sweet n Sour Chicken Jun 18 '12 at 18:46
@SweetnSourChicken - Glad that I could help. If this solution works for you, please click on the check box to accept the answer. How to ask questions? – Get Spatial Jun 18 '12 at 18:54
Well put. I just saw that there is an example of calculating centroids on this ArcGIS help page: help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//… – Timothy Michael May 16 '13 at 20:03

This should get you started hopefully: