Reputation: 41
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!
Upvotes: 3
Views: 6933
Reputation: 141
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()
Upvotes: 3
Reputation: 91
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)
Upvotes: 6
Reputation: 41
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.
Upvotes: 0
Reputation: 75
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.
Upvotes: -1