# How should I go about calculating the centroid of several lat long points in python, and perl?

Calculating the centroid several time on a number of geographical points. I was wonder is there a perl or python module that could make my life easier when working with large datasets of lat long points?

A coworker recommended using the perl module Math::Polygon, and that the polygon_centroid() function could be of some use, however I would like to know of other options.

-
Centroid for points? Easy: take the mean of each dimension. For polygons the algorithm is not so straight-forward. – Mike T Jul 12 '12 at 2:10

If you want to do this in Python I'd recommend the Shapely library. You could read all your points into a MultiPoint object, and every object in Shapley has a centroid property. A quick sample:

``````from shapely.geometry import MultiPoint
points = MultiPoint([(0.0, 0.0), (1.0, 1.0)])
print points.centroid #True centroid, not necessarily an existing point
print points.representative_point() #A represenative point, not centroid,
#that is guarnateed to be with the geometry.
``````

One thing to note - it's fine if all your lat-long data is in the same projection/datum, but Shapely is projection agnostic, so if your data needs to be projected you need to do it yourself before adding it.

-
Good point. The true area-weighted geographic centroid of a lat/long box (for example) is only equal to its planar centroid for small boxes near the equator. If the difference is important to you, transform your coordinates to an equal area projection first. – sgillies Jul 12 '12 at 20:08
I chuckled at the "good point" pun, Thanks for all your help, great feedback, and I am using the MultiPoint in python now :D – Beau Bouchard Jul 12 '12 at 22:18
I have same question however I want to calculate the centroid of a set of lines connected to each other. In arcpy I should use featureToPolygon_management where its output should be a feature class that I need to read it again and then find the centroid. I am wondering if there is a simpler way for it or not!!!!!! – msc87 Jul 31 '15 at 17:09

You might want to check out ESRI's help on working with geometry. You will want to use the Describe function and the shapeFieldName property. There are two properties for centroids that you can use. One is called centroid which is the true centroid if it is within or on the feature; otherwise, returns the label point (returns a point object). The other is called trueCentroid which returns the centre of gravity (centroid) regardless of whether it is actually within the shape or not.

-