Ajjit Narayanan
Ajjit Narayanan

Reputation: 692

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?

Upvotes: 4

Views: 4026

Answers (2)

Marlon Teixeira
Marlon Teixeira

Reputation: 393

It works for Point and Polygon either:

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

Upvotes: 2

Nicolas
Nicolas

Reputation: 363

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)

Upvotes: 0

Related Questions