TransWikia.com

Flipping coordinates with Shapely

Geographic Information Systems Asked by inc42 on April 20, 2021

I have Shapely geometries where latitude and longitude where mapped to X and Y the wrong way around. Latitude is mapped as X, longitude as Y. How can I fix the coordinates so that the current X and Y switch places?

2 Answers

You can use a simple transformation function with shapely.ops' transform function.

For example:

def flip(x, y):
    """Flips the x and y coordinate values"""
    return y, x

Example use:

>>> from shapely.geometry import *
>>> from shapely.ops import transform
>>> poly = box(*Point(1.23, 9.87).buffer(1).bounds)
>>> poly.wkt
'POLYGON ((2.23 8.87, 2.23 10.87, 0.23 10.87, 0.23 8.87, 2.23 8.87))'
>>> transform(flip, poly).wkt
'POLYGON ((8.87 2.23, 10.87 2.23, 10.87 0.23, 8.87 0.23, 8.87 2.23))'

Or if you prefer an even more functional approach you can use a lambda function like this:

transform(lambda x, y: (y, x), poly)

A potential third dimension is ignored by my examples as you did not mention that. I don't know what would happen to Z coordinates, I guess they would be dropped by my examples.

Correct answer by inc42 on April 20, 2021

For some reason the transform() function was not working for me. It was telling me I need to put I'm missing the 'x' and 'y' parameters. What did work for me however was this

gpd['list_poly'] = gpd.geometry.apply(lambda x: list(x.exterior.coords))
for ind,row in gpd.iterrows():
    list_poly = row.list_poly
    n_poly = [item[::-1] for item in list_poly]
    gpd.loc[ind,'reversed_geometery'] = Polygon(n_poly)

Answered by Hisham Sajid on April 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP