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?

BridgeSmith
  • 35
  • 1
  • 5

2 Answers2

1
import geopy
import pandas as pd

longlat = pd.read_csv("longlat.csv",encoding = 'utf-8', sep = '\t')
geolocator = geopy.Nominatim(user_agent="check_1")

def get_zip_code(x):
    location = geolocator.reverse("{}, {}".format(x['LATITUDE_X'],x['LONGITUDE_X']))
    return location.raw['address']['postcode']
longlat['zipcode'] = longlat.head().apply(lambda x: get_zip_code(x), axis = 1)
print(longlat.head())
   Unnamed: 0  LATITUDE_X  LONGITUDE_X     zipcode
0      124148   39.096232   -84.653337  45233-4555
1      124209   39.146201   -84.468843       45207
2      125298   39.134767   -84.499079       45267
3      125299   39.107625   -84.496675       45202
4      125390   39.092849   -84.388332       45230
Rafael Valero
  • 2,736
  • 18
  • 28
-2

You can use the following solution for an easy reverse geocoding for 'lat'/'lon' coordinates to zip code (No Paid API needed):

# Import packages
from uszipcode import SearchEngine
search = SearchEngine(simple_zipcode=True)
from uszipcode import Zipcode
import numpy as np

#Now to the real deal: the search function. This function can be #manually adapted to your needs (e.g., getting the full address instead of just ZIP codes)

#define zipcode search function
def get_zipcode(lat, long):
    result = search.by_coordinates(lat = lat, lng = lon, returns = 1)
    return result[0].zipcode

#load columns from dataframe
lat = df[‘Latitude’]
lon = df[‘Longitude’]

#define latitude/longitude for function
df = pd.DataFrame({‘lat’:lat, ‘lon’:lon})

#add new column with generated zip-code
df[‘zipcode’] = df.apply(lambda x: get_zipcode(x.lat,x.lon), axis=1)
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](/help/deleted-answers) – jmoerdyk Mar 22 '22 at 16:12