Adriana van Leeuwen
Adriana van Leeuwen

Reputation: 41

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!

Upvotes: 3

Views: 6933

Answers (4)

Francis Odero
Francis Odero

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

Kyriaki Mavropoulou
Kyriaki Mavropoulou

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

Adriana van Leeuwen
Adriana van Leeuwen

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

Gabriel Domene
Gabriel Domene

Reputation: 75

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.

Upvotes: -1

Related Questions