python - 如何从邮政编码中获取坐标并使用循环将它们添加到df中
问题描述
我有以下数据框:
d = {'Postcode': ['M3A','M4A','M5A','M6A','M9A','M1B'], 'Borough': ['North York', 'Downtown Toronto', 'Etobicoke',
'Scarborough', 'East York', 'York'],
'Neighbourhood': ['Parkwoods', 'Victoria Village', 'Harbourfront', 'Regent Park',
'Lawrence Heights', 'Lawrence Manor']}
post_df = pd.DataFrame(data = d)
产生类似的东西:
Postcode Borough Neighbourhood
0 M3A North York Parkwoods
1 M4A Downtown Toronto Victoria Village
2 M5A Etobicoke Harbourfront
3 M6A Scarborough Regent Park
4 M9A East York Lawrence Heights
5 M1B York Lawrence Manor
我想获取每个邮政编码的所有纬度和经度。我想出了这个代码来做到这一点:
import geocoder
# initialize your variable to None
lat_lng_coords = None
# loop until you get the coordinates
while(lat_lng_coords is None):
g = geocoder.google('{}, Toronto, Ontario'.format(postal_code_from_df))
lat_lng_coords = g.latlng
latitude = lat_lng_coords[0]
longitude = lat_lng_coords[1]
现在我的问题是:使用以前的代码,我想获取每个邮政编码的每个纬度和经度,并将它们添加到这个现有 df 中名为“纬度”和“经度”的 2 个新列中。我怎样才能使用单个循环来避免逐个搜索每个邮政编码坐标?
非常感谢您提前
解决方案
嗨,您需要定义您的地理编码器功能并将其循环到您的 df 上。我在函数中一一传递您的邮政编码列,并从地理编码器中获取值并将其分配并存储到两个新的纬度和经度列中。见下文:
import geocoder
def get_geocoder(postal_code_from_df):
# initialize your variable to None
lat_lng_coords = None
# loop until you get the coordinates
while(lat_lng_coords is None):
g = geocoder.google('{}, Toronto, Ontario'.format(postal_code_from_df))
lat_lng_coords = g.latlng
latitude = lat_lng_coords[0]
longitude = lat_lng_coords[1]
return latitude,longitude
for i in range(0,len(post_df)):
post_df['Latitude'][i],post_df['Longitude'][i]=get_geocoder(post_df.iloc[i]['Postcode'])
这应该适合你。
推荐阅读
- c - 如何更改 objdump 输出格式?
- python - 列值到单个字符串观察
- jenkins - jenkins 可以运行两个扩展 RtcExtensionProvider 的插件吗?
- javascript - 为 Podio 应用程序进行应用程序身份验证时收到 400 响应
- cpanel - Email Deliverability - Wrong Email in From section
- php - gmdate() 期望参数 2 为整数,给定浮点数
- bash - 使用 sed 将正则表达式替换为变量
- android - 使用 Google Vision API 扫描时无法录制视频
- javascript - 如何从数组中选择两个 div 元素并对其执行函数?
- wso2 - 如何在 wso2 中使用属性中介模式