Search code examples
pythonpandasgeocodegeopy

some coordinates that I extracted from geocoder in Python are not saving in the variable I created


enter code hereHi, I want to save some coordinates(latitude and longitudes) I extracted through geocodes, the problem I have is those coordinates are not saving and I can't seem to add them as columns to the table I generated using pandas

I get this error: AttributeError: 'NoneType' object has no attribute 'latitude'

    import pandas
    from geopy.geocoders import Nominatim
    df1= pandas.read_json("supermarkets.json")
    nom= Nominatim(scheme= 'http')
    lis= list(df1.index)
    for i in lis:

        l= nom.geocode(list(df1.loc[i,"Address":"Country"]))
        j=[]+ [l.latitude]
        k=[]+ [l.longitude]

I expect a way to get save the coordinates and include them in my table. Thanks


Solution

  • The nom.geocode(..) [geopy-doc] can result in a None given the address can not be found, or the query is not answered in sufficient time. This is specified in the documentation:

    Return type:

    None, geopy.location.Location or a list of them, if exactly_one=False.

    from operator import attrgetter
    
    locations = df['Address':'Country'].apply(
        lambda r: nom.geocode(list(r)), axis=1
    )
    nonnull = locations.notnull()
    df.loc[nonnull, 'longitude'] = locations[nonnull].apply(attrgetter('longitude'))
    df.loc[nonnull, 'latitude'] = locations[nonnull].apply(attrgetter('latitude'))

    We this first query all locations, and next we check what has been succesfull, and retrieve the latitude, and latitude for that location.