Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shapely point geometry in geopandas df to lat/lon columns

Tags:

I have a geopandas df with a column of shapely point objects. I want to extract the coordinate (lat/lon) from the shapely point objects to generate latitude and longitude columns. There must be an easy way to do this, but I cannot figure it out.

I know you can extract the individual coordinates like this:

lon = df.point_object[0].x
lat = df.point_object[0].y

And I could create a function that does this for the entire df, but I figured there was a more efficient/elegant way.

like image 408
jtam Avatar asked Apr 03 '18 16:04

jtam


2 Answers

If you have the latest version of geopandas (0.3.0 as of writing), and the if df is a GeoDataFrame, you can use the x and y attributes on the geometry column:

df['lon'] = df.point_object.x
df['lat'] = df.point_object.y

In general, if you have a column of shapely objects, you can also use apply to do what you can do on individual coordinates for the full column:

df['lon'] = df.point_object.apply(lambda p: p.x)
df['lat'] = df.point_object.apply(lambda p: p.y)
like image 88
joris Avatar answered Oct 24 '22 20:10

joris


Without having to iterate over the Dataframe, you can do the following:

df['lon'] = df['geometry'].x
df['lat'] = df['geometry'].y
like image 30
Mandi Avatar answered Oct 24 '22 21:10

Mandi