Search code examples
pythonpandaspolygonshapelywkt

Obtaining the center of a WKT polygon


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.


Solution

  • 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)