Back to Blog

Get full address from geo coordinates using Python for free

Piotr

Piotr

Founder

July 6, 2023
3 min read
address-main

Recently, I have been tasked to retrieve full addresses from geo coordinates for over 4k records. Nominatim is a great tool for this task, but it has a limit of 1 request per second.

You can read this on Medium here.

IMPORT LIBRARIES

1import pandas as pd
2from geopy.geocoders import Nominatim
3from geopy.extra.rate_limiter import RateLimiter
python

IMPORT DATA

1df = pd.read_csv("france_ria_locations.csv")
2
python

I imported csv file with geo coordinates to pandas DataFrame and I already had coords pair as a string. So, we will need to convert it to a tuple of floats, but first let's initialize Nominatim geocoder.

1# Initialize the geocoder
2geolocator = Nominatim(user_agent="myGeocoder")
python

and create a rate limiter:

1# Create a rate limiter
2geocode = RateLimiter(geolocator.reverse, min_delay_seconds=1)
python


CONVERT COORDS TO TUPLE OF FLOATS

1## convert 'coords' from string to a tuple of floats
2df['coords'] = df['coords'].apply(lambda x: tuple(map(float, x.strip('()').split(','))))
python

The next step is to add 'location' column to DataFrame by applying Nominatim geocoder to 'coords' column.

1# Add 'location' column to dataframe by applying geocode to 'coords' column
2df['location'] = df['coords'].apply(geocode)
python

SHAPING THE DATAFRAME

1# Add 'address', 'city' and 'zip' columns
2df['address'] = df['location'].apply(lambda loc: loc.raw['address']['road'] if 'road' in loc.raw['address'] else None)
3df['city'] = df['location'].apply(lambda loc: loc.raw['address']['town'] if 'town' in loc.raw['address'] else None)
4df['zip'] = df['location'].apply(lambda loc: loc.raw['address']['postcode'] if 'postcode' in loc.raw['address'] else None)
5
python

SAVE TO CSV

1# Save to csv
2df.to_csv('france_ria_locations_with_address.csv', index=False)
python

Happy coding!

Piotr

Piotr

About Piotr

Founder

Results-driven and forward-thinking Senior Leader in Payments, Banking & Finance with expertise in AI, Full Stack Development, and Python programming.