Search code examples
pythonerror-handlingcoordinatesgeocodinggeopy

Python GeoPy Error Handling


I am trying to convert some addresses to coordinates in a dataframe using GeoPy. Some addresses are not valid but i do not know which ones. Therefore i need the Library to skip the ones that are not valid or change them to Null or at least raise the exact field that is wrong.

The following works fine:

import pandas as pd
import geopy
from geopy.geocoders import Nominatim
geolocator = Nominatim()

df = pd.DataFrame({'city': ['south hampton', 'north park']})

df['CityCoordinates'] = df['city'].apply(geolocator.geocode,timeout=1000000).apply(lambda x: (x.latitude, x.longitude))

But the moment there is an invalid address the whole thing breaks:

df = pd.DataFrame({'city': ['south hampton', 'Southhamfdjhfdjhfgjgf', 'north park']})

df['CityCoordinates'] = df['city'].apply(geolocator.geocode, timeout=1000000).apply(lambda x: (x.latitude, x.longitude))

Other Libraries such as Geocoder also cant seem to handle exceptions. Lambda does not seem to allow error handling.

How can i work around this with exception handling.


Solution

  • You could call another function from your lambda that can do the error handling:

    df = pd.DataFrame({'city': ['south hampton', 'Southhamfdjhfdjhfgjgf', 'north park']})
    
    def eval_results(x):
        try:
            return (x.latitude, x.longitude)
        except:
            return (None, None)
    
    df['CityCoordinates'] = df['city'].apply(geolocator.geocode, timeout=1000000).apply(lambda x: eval_results(x))
    

    The result is something like this:

    0     (42.8809229, -70.9625558)
    1                  (None, None)
    2    (32.7408842, -117.1305876)