'Flipping longitude and latitude coordinates in GeoPandas

I'm working with datasets where latitudes and longitudes are sometimes mislabeled and I need to flip the longitudes and the latitudes. The best solution I could come up with is to extract the x an y coordinates using df.geometry.x and df.geometry.y, create a new geometry column, and reconstruct the GeoDataFrame using the new geometry column. Or in code form:

import geopandas
from shapely.geometry import Point

gdf['coordinates']  = list(zip(gdf.geometry.y, gdf.geometry.x))
gdf['coordinates'] = gdf['coordinates'].apply(Point)
gdf= gpd.GeoDataFrame(point_data, geometry='coordinates', crs = 4326)

This is pretty ugly, requires creating a new column and isn't efficient for large datasets. Is there an easier way to flip the longitude and latitude coordinates of a GeoSeries/ GeoDataFrame?



Solution 1:[1]

You can create the geometry column directly:

df['geometry'] = df.apply(lambda row: Point(row['y'], row['x']), axis=1)
df = gpd.GeoDataFrame(df, crs=4326)

Solution 2:[2]

It works for Point and Polygon either:

gpd.GeoSeries(gdf['coordinates']).map(lambda polygon: shapely.ops.transform(lambda x, y: (y, x), polygon))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicolas
Solution 2 Marlon Teixeira