5

I'm using pandas, and a dataset I obtained has a location column in a WKT format. For example:

hospital.get_value(1,'WKT')

POLYGON ((-58.4932 -34.5810,-58.4925 -34.5815,-58.4924 -34.5817))

There's a lot more points and with bigger precision in this example, but I shortened it for illustrative purposes. Also, I don't know whether it is a WKT or just a string. How do I obtain the center of this polygon so I can use it as a coordinate? Thanks in advance.

martincito
  • 71
  • 1
  • 5
  • It won't be the exact center but it will likely be within the polygon if you just average the longitudes together and average the latitudes together. Otherwise you would want to apply the centroid formula, and while the buildings are relativity small compared to the curvature of the earth naively applying such a formula in longitude and latitude space could introduce some error, to avoid this you would probably want to convert to Cartesian coordinates, apply the centroid formula, then convert back to longitude and latitude (ignoring the radial component). – kpie Sep 24 '17 at 16:00

1 Answers1

7

You almost have WKT, except that a polygons' linear ring needs to be closed.

Shapely has a .centroid property to get the center point:

from shapely import wkt
g = wkt.loads(
    'POLYGON ((-58.4932 -34.5810,-58.4925 -34.5815,-58.4924 -34.5817,-58.4932 -34.5810))')
print(g.centroid)  # POINT (-58.49270000000001 -34.5814)
print(g.centroid.coords[0])  # (-58.492700000000006, -34.581399999999995)
Mike T
  • 41,085
  • 18
  • 152
  • 203