Geocoding And Reverse Geocoding

Geocoding (converting a phyiscal address or location into latitude/longitude) and reverse geocoding (converting a lat/long to a phyiscal address or location) are common tasks when working with geo-data.

Python offers a number of packages to make the task incredibly easy. In the tutorial below, I use pygeocoder, a wrapper for Google's geo-API, to both geocode and reverse geocode.


First we want to load the packages we will want to use in the script. Specifically, I am loading pygeocoder for its geo-functionality, pandas for it's dataframe structures, and numpy for it's missing value (np.nan) functionality.

# Load packages
from pygeocoder import Geocoder
import pandas as pd
import numpy as np

Create some simulated geo data

Geo-data comes in a wide variety of forms, in this case we have a Python dictionary of five latitude and longitude strings, with each coordinate in a coordinate pair seperated by a comma.

# Create a dictionary of raw data
data = {'Site 1': '31.336968, -109.560959',
        'Site 2': '31.347745, -108.229963',
        'Site 3': '32.277621, -107.734724',
        'Site 4': '31.655494, -106.420484',
        'Site 5': '30.295053, -104.014528'}

While technically unneccesary, because I originally come from R, I am a big fan of dataframes, so let us turn the dictionary of simulated data into a dataframe.

# Convert the dictionary into a pandas dataframe
df = pd.DataFrame.from_dict(data, orient='index')
# View the dataframe
Site 5 30.295053, -104.014528
Site 1 31.336968, -109.560959
Site 3 32.277621, -107.734724
Site 4 31.655494, -106.420484
Site 2 31.347745, -108.229963

You can see now that we have a a dataframe with five rows, with each now containing a string of latitude and longitude. Before we can work with the data, we'll need to 1) seperate the strings into latitude and longitude and 2) convert them into floats. The function below does just that.

# Create two lists for the loop results to be placed
lat = []
lon = []

# For each row in a varible,
for row in df[0]:
    # Try to,
        # Split the row by comma, convert to float, and append
        # everything before the comma to lat
        # Split the row by comma, convert to float, and append
        # everything after the comma to lon
    # But if you get an error
        # append a missing value to lat
        # append a missing value to lon

# Create two new columns from lat and lon
df['latitude'] = lat
df['longitude'] = lon

Let's take a took a what we have now.

# View the dataframe
0 latitude longitude
Site 5 30.295053, -104.014528 30.295053 -104.014528
Site 1 31.336968, -109.560959 31.336968 -109.560959
Site 3 32.277621, -107.734724 32.277621 -107.734724
Site 4 31.655494, -106.420484 31.655494 -106.420484
Site 2 31.347745, -108.229963 31.347745 -108.229963

Awesome. This is exactly what we want to see, one column of floats for latitude and one column of floats for longitude.

Reverse Geocoding

To reverse geocode, we feed a specific latitude and longitude pair, in this case the first row (indexed as '0') into pygeocoder's reverse_geocoder function.

# Convert longitude and latitude to a location
results = Geocoder.reverse_geocode(df['latitude'][0], df['longitude'][0])

Now we can take can start pulling out the data that we want.

# Print the lat/long
(30.30077769999999, -104.0129162)
# Print the city
# Print the country
'United States'
# Print the street address (if applicable)
# Print the admin1 level


For geocoding, we need to submit a string containing an address or location (such as a city) into the geocode function. However, not all strings are formatted in a way that Google's geo-API can make sense of them. We can text if an input is valid by using the .geocode().valid_address function.

# Verify that an address is valid (i.e. in Google's system)
Geocoder.geocode("7250 South Tucson Boulevard, Tucson, AZ 85756").valid_address

Because the output was True, we now know that this is a valid address and thus can print the latitude and longitude coordinates.

# Print the lat/long
(30.30077769999999, -104.0129162)

But even more interesting, once the address is processed by the Google geo API, we can parse it and easily seperate street numbers, street names, etc.

# Find the lat/long of a certain address
result = Geocoder.geocode("7250 South Tucson Boulevard, Tucson, AZ 85756")
# Print the street number
# Print the street name
'South Tucson Boulevard'

And there you have it. Python makes this entire process easy and inserting it into an analysis only takes a few minutes. Good luck!