Home > OS >  How to apply Geopy in a pandas column?
How to apply Geopy in a pandas column?

Time:09-30

My DataFrame 'df' has a column df['Cidade'] with cities names and I want to find out the latitute and longitude of every single city using Geopy. The following code works for a single city input:

address='Pacoti'
geolocator = Nominatim(user_agent="Your_Name")
location = geolocator.geocode(address)
print(location.address)
print((location.latitude, location.longitude))

output:

Pacoti, Região Geográfica Imediata de Redenção-Acarape, Região Geográfica Intermediária de Fortaleza, Ceará, Região Nordeste, 62770-000, Brasil (-4.2253561, -38.9208352)

So I tried to create a function:

def lat_long(x):
  address= x
  geolocator = Nominatim(user_agent="Your_Name")
  location = geolocator.geocode(address)
  return location.latitude, location.longitude

then I used 'map' function:

df['Cidade'].map(lat_long)

But I'm getting the following error:

AttributeError: 'NoneType' object has no attribute 'latitude'

What am I doing wrong?

CodePudding user response:

There may be a "bad" entry in that dataframe as you're mapping them all in which is giving you a none object when going for the objects lat and long. Check to see if this is case and give you an idea for fixing it:

if location is none:
  print("something")

CodePudding user response:

On the following question:

How to apply Geopy in a pandas column using apply() method?

the code for initializing geopy on pandas has the solution for the 'NoneType problem'.

(Still can't Apply to my column's dataframe :(, HELP!!!)

  • Related