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