Getting the wrong location data using GeoPy Geocoders with Python

Viewed 23

I am very new to python and I am trying to run a csv of zip codes with geopy that will give me the city, state, country. I import the file and run the packet then add a column Address. I want to have all the cities in the city column, state in state column, country in country column etc. I have got the code below to run and splits the address, but not by category just by the delimiter. Could anyone help me with this?

import csv
import pandas as pd
from geopy.geocoders import Nominatim

test_filename='test.csv'
df=pd.read_csv(test_filename, dtype=object, index_col = 1)
df.head()

geolocator = Nominatim(user_agent="user_me")

from geopy.extra.rate_limiter import RateLimiter
geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
Address = geolocator.geocode("Billing Zip")
df['Address'] = df["Billing Zip"].apply(geocode)
df['Address'] = df['Address'].astype(str).str.replace('.', '')

df[['City', 'County', 'State', 'Zip Code', 'Country', ' ', ' ']] = df.Address.str.split(',' , expand = True)
print(df.head())

Below is what the output look like:

Billing Zip Address City State Country
10006 Manhattan, City of New York, New York, United States New York New York United States
93049 Bayern, Deutschland Bayern Deutschland
95684 California, United States California United States

I would like the output to be:

Billing Zip Address City State Country
10006 Manhattan, City of New York, New York, United States New York New York United States
93049 Bayern, Deutschland Bayern Deutschland
95684 California, United States California United States

How would be the best way to do this?

Thank you!

1 Answers

Use addressdetails=True parameter to get a dictionary defining each part of the location separately:

# importing geopy library
from geopy.geocoders import Nominatim
 
# calling the Nominatim tool
loc = Nominatim(user_agent="GetLoc")
 
# entering the location name
getLoc = loc.geocode("Wawel, Kraków", addressdetails=True)
 
# printing address
print(getLoc.raw['address'])

print(getLoc.raw['address']['city'])
print(getLoc.raw['address']['state'])
print(getLoc.raw['address']['country'])

If the you enter a location for which any field is not specified this will raise a KeyError, so you might need to except that and fill with Empty/NaN value.

Related