1

I have a data frame of latitude and longitude coordinates on this CSV file:Longlat.

I used this code to try to get the zipcodes:

import copy

def get_zipcode(df, geolocator, lat_field, lon_field):
    location = geolocator.reverse((df[lat_field], df[lon_field]))
    return location.raw['address']['postcode']


geolocator = geopy.Nominatim(user_agent='myusername') #My OpenMap username

zipcodes = longlat.apply(get_zipcode, axis=1, geolocator=geolocator, lat_field=longlat['LATITUDE_X'], lon_field=longlat['LONGITUDE_X'])

I got the error:

KeyError
"None of [Float64Index([39.0962320000896, 39.1462010000896, 39.1347670000896,\n 39.1076250000897, 39.0928490000897, 39.1648900000896,\n 39.1846440000895, 39.0970790000897, 39.1491220000896,\n 39.1145560000896,\n ...\n 39.1039560000896,

How do I fix it?

1
  • I still get the same error Feb 11, 2021 at 10:58

1 Answer 1

2

You are passing in the latitude and longitude Series instead of the latitude and longitude column names.

import geopy
import pandas as pd

def get_zipcode(df, geolocator, lat_field, lon_field):
    try:
        location = geolocator.reverse((df[lat_field], df[lon_field]))
        return location.raw['address']['postcode']
    except (AttributeError, KeyError, ValueError):
        print(repr(e), df[lat_field], df[lon_field])
        return None



longlat = pd.read_csv('longlat.csv', sep='\t')
geolocator = geopy.Nominatim(user_agent='myusername') #My OpenMap username

# Change this
# zipcodes = longlat.apply(
#     get_zipcode, axis=1,geolocator=geolocator, 
#     lat_field=longlat['LATITUDE_X'], lon_field=longlat['LONGITUDE_X'])

# To this
zipcodes = longlat.apply(
    get_zipcode, axis=1, geolocator=geolocator, 
    lat_field='LATITUDE_X', lon_field='LONGITUDE_X')


print(zipcodes)

Output:

0    45233-4555
1    45212-2609
2    45229-3018
3         45202
4         45230
...
dtype: object
11
  • I'm having the error: key error 'postcode' Feb 11, 2021 at 16:54
  • 2
    Obviously it can't find a code for that coord, wrap the return location.raw['address']['postcode'] in a try: except:
    – user2856
    Feb 11, 2021 at 20:50
  • I got the error: Must be a coordinate pair or Point Can I get the zipcodes from the shapefile of Ohio instead of this method? Feb 12, 2021 at 16:08
  • How about you post more complete code. I ran the code in my answer on a portion of your csv and it works.
    – user2856
    Feb 12, 2021 at 22:47
  • Are you on kaggle? I can share the notes with you so that you can see what I'm trying to do. The datasets are quite large. Feb 13, 2021 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.