# How to compute weighted centroids in PostGIS?

I have a group of points and each point has an associated count value. How can I calculate the centroid of the group weighted by the values associated to each point?

There is an answer on StackOverflow that gives a mathematical, but not a Postgres answer. Translating to Postgres/Postgis, you could try something like this:

``````select sum(st_x(pt)*weight)/sum(weight) as cx from weighted_points;
select sum(st_y(pt)*weight)/sum(weight) as cy from weighted_points;
``````

Or if you want a point back, then,

``````select st_makepoint(x.cx, y.cy) from
(select sum(st_x(pt)*weight)/sum(weight) as cx from weighted_points) x,
(select sum(st_y(pt)*weight)/sum(weight) as cy from weighted_points) y
``````

Using Fréchet Mean as a basis for this, you could try something like the following

``````SELECT EXP(SUM(LN(X)*W)/SUM(W)) weightedMedianX,
EXP(SUM(LN(Y)*W)/SUM(W)) weightedMedianY,
EXP(SUM(LN(X))/COUNT(*)) medianX,
EXP(SUM(LN(Y))/COUNT(*)) medianY
FROM PointTable
``````