如何根据 python 上的经度和纬度获取邮政编码?

How do I get zipcodes from longitude and latitude on python?

我在这个 CSV 文件上有一个纬度和经度坐标的数据框:Longlat

我使用此代码尝试获取邮政编码:

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'])

我收到错误:

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,

我该如何解决?

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

您可以使用以下解决方案将 'lat'/'lon' 坐标轻松反向地理编码为邮政编码(无需付费 API):

# 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)