我有一个大约100k行的数据与邮政编码和国家代码。我想得到每个位置的纬度和经度,并将其保存在两个新列中。我在dataframe的示例上有一个工作代码(例如100行),但是在所有dataframe上运行它需要这么长时间(>1小时)。我是Python新手,我怀疑应该有一种更快的方法来做到这一点:
postcode和country_code,我查询了两次,一次是纬度,一次是经度。我非常确信我不应该这样做(也就是说,我可以在每行进行一个查询,并创建纬度和经度列,accordingly).get_lat(pcode, country)和get_long(pcode, country),并在数据上应用是没有效率的。下面是我的代码的一个例子。
import pgeocode
import numpy as np
import pandas as pd
#Sample data
df = pd.DataFrame({'postcode':['3011','3083','3071','2660','9308','9999'], 'country_code': ['NL','NL','NL','BE','BE','DE']})
#There are blank postcodes and postcodes that pgeocode cannot return any value, so I am using try-except (e.g. last row in sample dataframe):
#function to get latitude
def get_lat(pcode, country):
try:
nomi = pgeocode.Nominatim(country)
x = nomi.query_postal_code(pcode).latitude
return x
except:
return np.NaN
#function to get longitude
def get_long(pcode, country):
try:
nomi = pgeocode.Nominatim(country)
x = nomi.query_postal_code(pcode).longitude
return x
except:
return np.NaN
#Find and create new columns for latitude-longitude based on postcode (ex: 5625) and country of postcode (ex: NL)
df['latitude'] = np.vectorize(get_lat)(df['postcode'],df['country_code'])
df['longitude'] = np.vectorize(get_long)(df['postcode'],df['country_code'])发布于 2021-11-10 12:52:52
作为另一种解决方案,我从以下网站下载了txt文件:http://download.geonames.org/export/zip/
下载文件后,只需导入txt文件并加入即可。它要快得多,但却是静态的,也就是说,您在早期使用邮政编码数据库的快照。
另一个优点是您可以检查文件和检查邮政编码的格式。在使用pgeocode时,很难跟踪已接受的邮政编码格式,也很难理解查询为什么返回null。
https://stackoverflow.com/questions/68832133
复制相似问题