How to calculate centroid of x,y coordinates in python

Martin Petri Bagger picture Martin Petri Bagger · Oct 30, 2013 · Viewed 16.8k times · Source

I have got a lot of x,y coordinates which I have clustered based on the distance between them. Now I would like to calculate a centroid measure for each cluster of x,y coordinates. Is there a way to do this?

My coordinates are in the format:

    coordinates_cluster = [[x1,x2,x3,...],[y1,y2,y3,...]]

Each cluster has a minimum length of three points, and all points can have both negative and positive x and y values. I hope that someone can help me.

Best, Martin

(I am using python 2.7 with canopy 1.1.1 (32 bit) on a Windows 7 system.)

Answer

Martin Petri Bagger picture Martin Petri Bagger · Oct 30, 2013

I realized that it was not that hard, but here is the code for calculating centroids of x,y coordinates:

    >>> c = [[1,4,-5],[3,-2,9]] # of the form [[x1,x2,x3],[y1,y2,y3]]
    >>> centroide = (sum(c[0])/len(c[0]),sum(c[1])/len(c[1]))

    >>> centroide
    (0, 3)