Turn geometry column into lat/long columns in Geodataframe

Viewed 3449

I have a Geodataframe with a 'geometry' column in which I have point geometries, e.g. POINT (-0.01334 51.52883). I need to extract the latitude and longitude and add it as new columns in the dataframe.

I tried using

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

but it gives me a SettingWithCopyWarning and I'm not sure why. Can anybody help please? Thank you!

4 Answers

You can try directly apply the lan/lon extraction to the df like this:

df['lon'] = df.geometry.apply(lambda p: p.x)
df['lat'] = df.geometry.apply(lambda p: p.y)

I did this way and had no issue:

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

and selected the two columns created:

df = df[['lon','lat']]
df.dropna()

The problem wasn't with the code posted - it was to do with slicing the original dataframe several times prior to running this code, as per the comment by martinfleis. I avoided the SettingWithCopyWarning by dropping rows I didn't need from the original dataframe rather than slicing.

Considering that the values are string in the format described (lat lon) you can replace the parenthesis first to better view.

  1. df["geo"] = df["geo"].str.replace(r"[\(\)", "") enter image description here

After that, you can split by the space char in the middle and expand the columns. str.split doc

  1. df = df["geo"].str.split(" ", expand=True)

    str.split

You'll end up with two columns 0 and 1, just need to rename them after that.

Related