【发布时间】:2021-10-20 05:38:06
【问题描述】:
我有一个大约 10 万行的数据框,其中包含邮政编码和国家/地区代码。我想获取每个位置的纬度和经度并将其保存在两个新列中。我有一个关于数据帧样本的工作代码(例如 100 行),但在所有数据帧上运行它需要很长时间(> 1 小时)。我是 Python 新手,我怀疑应该有一种更快的方法来做到这一点:
- 对于给定的
postcode和country_code,我查询了两次,一次是纬度,一次是经度。我非常确信我不应该这样做(即我可以每行进行一个查询并相应地创建纬度和经度列)。 - 我定义函数
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'])
【问题讨论】:
标签: python pandas latitude-longitude postal-code