'Turn geometry column into lat/long columns in Geodataframe
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!
Solution 1:[1]
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.
Solution 2:[2]
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)
Solution 3:[3]
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()
Solution 4:[4]
Considering that the values are string in the format described (lat lon) you can replace the parenthesis first to better view.
After that, you can split by the space char in the middle and expand the columns. str.split doc
You'll end up with two columns 0 and 1, just need to rename them after that.
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 | Adriana van Leeuwen |
| Solution 2 | Kyriaki Mavropoulou |
| Solution 3 | Francis Odero |
| Solution 4 | Gabriel Domene |


